C# await Task.Factory.StartNew(() => vs Task.Start; await Task;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17001448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:19:33  来源:igfitidea点击:

await Task.Factory.StartNew(() => versus Task.Start; await Task;

c#async-awaitc#-5.0

提问by user42

Is there any functional difference between these two forms of using await?

这两种使用 await 的形式在功能上有区别吗?

  1. string x = await Task.Factory.StartNew(() => GetAnimal("feline"));
    
  2. Task<string> myTask = new Task<string>(() => GetAnimal("feline"));
    myTask.Start();
    string z = await myTask;
    
  1. string x = await Task.Factory.StartNew(() => GetAnimal("feline"));
    
  2. Task<string> myTask = new Task<string>(() => GetAnimal("feline"));
    myTask.Start();
    string z = await myTask;
    

Specifically, in what order is each operation called in 1.? Is StartNew called and then is await called, or is await called first in 1.?

具体来说,在 1. 中调用每个操作的顺序是什么?是先调用 StartNew 然后调用 await,还是在 1 中先调用 await?

采纳答案by Brian Rasmussen

StartNewis just a short hand for creating and starting a task. If you want to do something to the Taskinstance before you start it, use the constructor. If you just want to create and start the task immediately, use the short hand.

StartNew只是创建和启动任务简写。如果您想Task在启动实例之前对其进行某些操作,请使用构造函数。如果您只想立即创建并启动任务,请使用简写。

Documentation for StartNewsays:

文档StartNew说:

Calling StartNew is functionally equivalent to creating a task by using one of its constructors, and then calling the Task.Start method to schedule the task for execution.

调用 StartNew 在功能上等同于使用其构造函数之一创建任务,然后调用 Task.Start 方法来安排任务执行。

回答by Stephen Cleary

When you're writing code with asyncand await, you should use Task.Runwhenever possible.

使用async和编写代码时await,应Task.Run尽可能使用。

The Taskconstructor (and Task.Start) are holdovers from the Task Parallel Library, used to create tasks that have not yet been started. The Taskconstructor and Task.Startshould not be used in asynccode.

Task构造函数(和Task.Start)从任务并行库,用于创建尚未启动的任务遗留下来的。该Task构造和Task.Start不应该使用async的代码。

Similarly, TaskFactory.StartNewis an older method that does not use the best defaults for asynctasks and does not understand asynclambdas. It can be useful in a few situations, but the vast majority of the time Task.Runis better for asynccode.

同样,TaskFactory.StartNew是一种较旧的方法,它不使用async任务的最佳默认值并且不理解asynclambda。它在少数情况下很有用,但绝大多数时间Task.Run更适合async代码。