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

标签 c# parallel-processing task wait task-parallel-library

我看到的几乎所有关于使用 C# 4.0 Task.Factory.StartNew 的文档都指出,为了等待任务完成,您需要等待。但我的初步测试表明这是不必要的。其他人可以给我确认吗?我很好奇为什么有那么多在线和打印的引用资料说您应该调用 Wait。

这是一个简单的控制台应用程序,显示我不需要 Wait 语句,因此我将其注释掉。无论我是否注释掉 tsk.Wait(),输出都是一样的。

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

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

The code:

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();
    }
}

最佳答案

如果您只想等待任务完成,建议的做法是调用 .Wait() .对于 Task (与 Task<T> 相对)这是唯一的选择。

对于 Task<T> , 但是,还有 .Result等待,这就是您正在使用的。因此,在您的情况下,无需调用 .Wait() .

关于c# - 使用 Task.Factory.StartNew() 后是否需要 Wait()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4673062/

相关文章:

scala - Scala 中的执行上下文是什么?

c++ - Prim 和 Boruvka 的最小生成树算法

c# - DotNetZip 取消任务中的提取

java - JEE 7 Scheduler如何在不阻塞调度程序的情况下 fork 任务

c - 具有依赖关系的数组中的并行操作

c# - 使用 webClient C# 在异步文件下载中将文件名传递给 DownloadFileCompleted

c# - 从MVP中的模型子组件返回错误消息

c# - Firebird 数据库上的错误 MaxPoolSize

c# - 将 int(或任何值类型)存储为对象并将它们转换回 int(或值类型)是否有任何成本?

python - 无法在 <module 'abc' from '__main__' > 上获取属性 'abc_h.py' >