简体   繁体   English

Task.ContinueWith在任务完成执行之前运行

[英]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 . 所以我们假设我有一个名为tTask和一个名为aAction<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: 我用的是什么:

  • Windows 8 RTM Windows 8 RTM
  • .NET Framework 4.5 .NET Framework 4.5

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM