进程结束前任务未完成 [英] Tasks not finishing before process end

查看:123
本文介绍了进程结束前任务未完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在主线程的代码中,我调用了第三方API.对于API的每个结果,我都会调用2个异步任务.有时,所有工作都能正常运行,有时,并非所有异步任务都在运行.我想当主线程完成时,垃圾收集器将杀死我在后台运行的所有其他任务.有什么办法告诉垃圾回收器不要在主线程结束时终止后台服务?

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?

代码如下:

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;
     }

谢谢

推荐答案

如果要等待所有任务完成,则必须收集它们并等待它们.因为当您的过程结束时,通常这就是一切的结束.

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());

您还具有 2 级别的粗心(意味着您开始执行任务,并不关心是否已完成).您也需要删除第二个:

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);
}

这篇关于进程结束前任务未完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆