问题
In my code in the main thread I call a 3rd party API. For each result from the API I call 2 async tasks. Sometimes all works perfectly, sometimes not all async tasks run. I suppose that when the main thread finishes, the garbage collector kills all my other tasks that run in the background. Is there any way to tell garbage collector not to kill the background services when the main thread finishes?
The code is like this:
for (int i = 0; i < 1000; i++)
{
var demo = new AsyncAwaitTest();
demo.DoStuff1(guid);
demo.DoStuff2(guid);
}
public class AsyncAwaitTest
{
public async Task DoStuff1(string guid)
{
await Task.Run(() =>
{
DoSomething1(guid);
});
}
public async Task DoStuff2(string guid)
{
await Task.Run(() =>
{
DoSomething2(guid);
});
}
private static async Task<int> DoSomething1(string guid)
{
// insert in db or something else
return 1;
}
private static async Task<int> DoSomething2(string guid)
{
// insert in db or something else
return 1;
}
Thanks
回答1:
If you want to wait for all your tasks to finish, you have to collect them and wait for them. Because when your process ends, that normally is the end of everything.
var tasks = List<Task>();
for (int i = 0; i < 1000; i++)
{
var demo = new AsyncAwaitTest();
tasks.Add(demo.DoStuff1(guid));
tasks.Add(demo.DoStuff2(guid));
}
// before your process ends, you need to make sure all tasks ave finished.
Task.WaitAll(tasks.ToArray());
You also have 2 levels of carelessness (meaning you start a task and don't care whether it's done). You need to remove the second one, too:
public async Task DoStuff1(string guid)
{
await DoSomething1(guid);
}
来源:https://stackoverflow.com/questions/47453915/tasks-not-finishing-before-process-end