Equivalent of Ihostedservice in asp.net framework for background tasks

前端 未结 2 839
忘了有多久
忘了有多久 2021-02-04 03:59

I have a restful micro service (web api) in .net 4.6.2 and I want to call a fire and forget function each time after certain endpoints are called to do some database cleanup wor

2条回答
  •  無奈伤痛
    2021-02-04 04:27

    One of the safest ways to proceed would be to use a Thread. You can fire the thread ans let it run.

    If you need the thread to get killed in case the App closed, You can add the isBackground parameter.
    Otherwise, the thread should continue to run until its work is finished

    Thread backgroundThread = new Thread(() => 
    {
        Console.WriteLine("I'll run until the app Stops or I finish working");
        LongRunningJob();
    }, IsBackground = true);
    
    Thread foregroundThread = new Thread(() => 
    {
        Console.WriteLine("I'll stop when I'm finished");
        LongRunningJob();
    }
    backgroundThread.Start();
    foregroundThread.Start()
    

提交回复
热议问题