[英]Task.ContinueWith runs before the task finishes executing
In Main
method of a console application: 在控制台应用程序的Main
方法中:
Do().ContinueWith(t => Do())
.ContinueWith(t => Do())
.ContinueWith(t => Do());
Do
is a method that returns Task
: Do
是一个返回Task
的方法:
var source = new CancellationTokenSource();
var token = source.Token;
return Task.Factory.StartNew(() =>
{
Console.WriteLine("Inside " + _Counter);
token.WaitHandle.WaitOne(1000);
Console.WriteLine(_Counter++ + " is done");
}, token);
And _Counter
is an integer field: _Counter
是一个整数字段:
private static int _Counter = 1;
When I run, the result is this: 当我跑步时,结果如下:
Inside 1 里面1
1 is done 1完成了
Inside 2 里面2
Inside 2 里面2
Inside 2 里面2
2 is done 2完成了
3 is done 3完成了
4 is done 4完成了
So let's assume I have a Task
called t and an Action<Task>
called a . 所以我们假设我有一个名为t的Task
和一个名为a的Action<Task>
。
If I call t.ContinueWith(a)
, a should be called after t completes, right? 如果我叫t.ContinueWith(a)
, 一个应该被T完成后调用,对不对? And when a runs, that should mean whatever delegate t calls has ended. 而当运行,这应该意味着任何委托T公司的已经结束。
What causes this result? 是什么导致这个结果? Am I not getting something obvious here? 我在这里没有明显的东西吗?
What I use: 我用的是什么:
If I call t.ContinueWith(a), a should be called after t completes, right? 如果我调用t.ContinueWith(a),应该在t完成后调用,对吧?
Sure. 当然。 But since your Do
function creates a new task, it completes immediately, thus starting the next Do
. 但是由于你的Do
函数创建了一个新任务,它立即完成,从而启动下一个Do
Remove the task creation from Do
(leaving only the Console.WriteLine stuff) and it should work as expected. 从Do
删除任务创建(只保留Console.WriteLine的东西),它应该按预期工作。
static void Do()
{
Console.WriteLine("Inside " + _Counter);
Thread.Sleep(1000);
Console.WriteLine(_Counter + " is done");
}
static void Main(string[] args)
{
Task.Factory.StartNew(Do)
.ContinueWith(t => Do())
.ContinueWith(t => Do())
.ContinueWith(t => Do());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.