How to create a new Task of type Task?

こ雲淡風輕ζ 提交于 2020-01-30 13:10:12

问题


I have:

async Task doWork() { Console.WriteLine("do some async work in this method"); }

Task task = new Task(doWork);   //line X
task.Start();
task.Wait();

Line X gives a compilation error:

CS0407 'Task Form1.doWork()' has the wrong return type

How do I instantiate a new Task doWork?

I am able to use the following but it gives me a different set of problems.

Task task = doWork();
task.Wait();

I want to avoid this second method. How do I instantiate a new Task of type async Task at line X?


回答1:


Since doWork() has a return type of Task, the declaration needs to be an instance of the generic Task<TResult> - i.e. Task<Task>




回答2:


In this case, what you probably want is to define doWork to have the return type of void. Then you can initialize task as you've shown using the Task constructor with an argument of Action (see docs).

Alternatively, you can use

Task task = doWork();

See here for a discussion of the tradeoffs between the two techniques.



来源:https://stackoverflow.com/questions/45363922/how-to-create-a-new-task-of-type-task

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