问题
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