使用Task.Factory.StartNew()后是否需要Wait()?

Tam*_*Bui 9 c# parallel-processing task wait task-parallel-library

我在使用C#4.0 Task.Factory.StartNew时看到的几乎所有文档都指出,为了等待Task完成,你需要一个Wait.但我的初步测试表明这是不必要的.其他人可以给我确认吗?我很好奇为什么这么多在线和印刷的参考文献说你应该打电话给Wait.

这是一个简单的控制台应用程序,显示我不需要Wait语句,所以我评论了它.无论我是否注释掉tsk.Wait(),输出都是一样的.

所有情况下的预期产出如下:

Main thread starting.
After running MyTask. The result is True
After running SumIt. The result is 1
Main thread ending.

代码:

class Program
{
    // A trivial method that returns a result and takes no arguments.
    static bool MyTask()
    {
        Thread.Sleep(2000);
        return true;
    }

    // This method returns the summation of a positive integer
    // which is passed to it.
    static int SumIt(object v)
    {
        int x = (int)v;
        int sum = 0;
        for (; x > 0; x--)
            sum += x;
        return sum;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Main thread starting.");
        // Construct the first task.
        Task<bool> tsk = Task<bool>.Factory.StartNew(() => MyTask());
        // I found this Wait statement to be completely unnecessary.
        //tsk.Wait();
        Console.WriteLine("After running MyTask. The result is " +
        tsk.Result);
        // Construct the second task.
        Task<int> tsk2 = Task<int>.Factory.StartNew(() => SumIt(1));
        Console.WriteLine("After running SumIt. The result is " +
        tsk2.Result);
        tsk.Dispose();
        tsk2.Dispose();
        Console.WriteLine("Main thread ending.");
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*mwi 19

如果您只想等待任务完成,建议的操作方法是致电.Wait().对于a Task(而不是a Task<T>),这是唯一的选择.

对于一个Task<T>,但是,也有.Result,这也是等待,这是你使用的是什么.所以在你的情况下,没有必要打电话.Wait().