任务不等待 ContinueWith 完成 [英] Task does not wait for ContinueWith to finish

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

问题描述

我有如下控制台应用程序和代码,

I have console application and code as below,

我的问题是在ContinueWith任务完成之前,控制台应用程序结束,它没有等待continueWith完成,请指教.

My problem is before ContinueWith task finish, the console application ends, it does not waits the continueWith to finish, please advise.

请让我知道我遗漏了什么或不正确的地方.

Please let me know what I am missing or incorrect.

var task1 = Task<bool>.Factory.StartNew(() => DoProcess());

task1 .ContinueWith(
     t1 => updateSuccess(),
       TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

task1 .ContinueWith(
     t => updateFault(),
     TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

task1.Wait();

推荐答案

你必须等待任务从主线程完成.简化它看起来像

You have to wait on the task to complete from the main thread. Simplified it'll look like

var task1 = Task<bool>.Factory.StartNew(() => DoProcess());

successContinuation = task1 .ContinueWith(t1 => updateSuccess(),
                                          TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.ExecuteSynchronously)
failureContinuation = task1 .ContinueWith( t => updateFault(),
                                          TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

Task.WaitAny(successContinuation, failureContinuation);

我认为您没有意识到您正在创建一个将(实际上只是可能)在不同线程中执行的任务.当你开始你的任务时,你有两个不同的执行线程,主线程和你的任务将继续运行.如果您希望您的主线程(您的控制台应用程序)等待任务完成,您必须手动指定它.

I think you're not realizing that you're creating a task that will (actually just may) execute in a different thread. The moment you start your task you have two different threads of execution the main thread, which will continue to run, and your task. If you want your main thread (your console application) to wait for the task to finish, you have to manually specify it.

这篇关于任务不等待 ContinueWith 完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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