。继续启动任务完成之前, [英] .Continue starts before task is completed
问题描述
我有以下的code在C#中,VS2012,WPF 4.5。
我的期望是如此, .ContinueWith
会后,任务完成完全执行(这是一个延续的全部目的,是不是?)。
I have the following code in C#, VS2012, WPF 4.5.
My expectation would be that, .ContinueWith
will be executed after the task has finished completely (that's a continuation's whole purpose, isn't it?).
这应该导致2的值 finalResult
。
int myTestInt = 0;
Task task = Task.Factory.StartNew(async () =>
{
myTestInt = 1;
await Task.Delay(TimeSpan.FromSeconds(6));
myTestInt = 2;
}).ContinueWith(_ =>
{
int finalResult = myTestInt;
});
其实, finalResult
分配值1来代替。因此,它似乎是继续开始在等待
语句了。
In fact, finalResult
is assigned a value of 1 instead. So it seems like the continuation is started on the await
statement already.
这是预期的行为?我失去了一些东西呢?我不能靠 ContinueWith
启动后的任务已经彻底完蛋了?
Is this the intended behaviour? Am I missing something here? Can't I rely on ContinueWith
to start after a task has completely finished?
更新:
贾斯汀的回答只是激励我检查以下内容:
Justin's answer just inspired me to check the following:
int myTestInt = 0;
Task task=Task.Factory.StartNew(async () =>
{
myTestInt = 1;
await Task.Delay(TimeSpan.FromSeconds(6));
myTestInt = 2;
});
task.Wait();
int result2 = myTestInt;
finalResult仍然设置为1。请问有没有办法可靠地等待包含等待
s到完成?
推荐答案
当你传递一个异步
授人以 Task.Factory.StartNew
,返回工作
仅重presents该委托的第一部分(直到一次等待
件事情是不是已经完成)。
When you pass an async
delegate to Task.Factory.StartNew
, the returned Task
only represents the first portion of that delegate (up until the time it await
s something that is not already completed).
不过,如果你传递一个异步
委托给新的 Task.Run
方法(该方法被列入此原因),则返回工作
重presents整个委托。所以,你可以使用 ContinueWith
如您所愿。 (虽然等待
通常比一个更好的选择 ContinueWith
)。
However, if you pass an async
delegate to the new Task.Run
method (which was included for this reason), the returned Task
represents the entire delegate. So you can use ContinueWith
as you expect. (Although await
is usually a better option than ContinueWith
).
有关 StartNew
VS 运行
的详细信息,请参阅斯蒂芬Toub关于这个专题的的帖子。
For more information on StartNew
vs Run
, see Stephen Toub's post on the topic.
这篇关于。继续启动任务完成之前,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!