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

血红的双手。 提交于 2019-11-29 01:52:54

问题


Is there any functional difference between these two forms of using 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;
    

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 is just a short hand for creating and starting a task. If you want to do something to the Task instance before you start it, use the constructor. If you just want to create and start the task immediately, use the short hand.

Documentation for StartNew says:

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.




回答2:


When you're writing code with async and await, you should use Task.Run whenever possible.

The Task constructor (and Task.Start) are holdovers from the Task Parallel Library, used to create tasks that have not yet been started. The Task constructor and Task.Start should not be used in async code.

Similarly, TaskFactory.StartNew is an older method that does not use the best defaults for async tasks and does not understand async lambdas. It can be useful in a few situations, but the vast majority of the time Task.Run is better for async code.



来源:https://stackoverflow.com/questions/17001448/await-task-factory-startnew-versus-task-start-await-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!