如何创建Task类型的新Task? [英] How to create a new Task of type Task?
本文介绍了如何创建Task类型的新Task?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
async Task doWork() { Console.WriteLine("do some async work in this method"); }
Task task = new Task(doWork); //line X
task.Start();
task.Wait();
第X行给出了编译错误:
Line X gives a compilation error:
CS0407'任务Form1.doWork()'的返回类型错误
CS0407 'Task Form1.doWork()' has the wrong return type
如何实例化新任务 doWork
?
我可以使用以下内容,但这给我带来了一系列不同的问题.
I am able to use the following but it gives me a different set of problems.
Task task = doWork();
task.Wait();
我想避免第二种方法.如何在X行实例化类型为 async Task
的新 Task
?
I want to avoid this second method. How do I instantiate a new Task
of type async Task
at line X?
推荐答案
由于doWork()的返回类型为 Task
,因此声明必须是通用 Task<的实例.TResult>
-即 Task< Task>
Since doWork() has a return type of Task
, the declaration needs to be an instance of the generic Task<TResult>
- i.e. Task<Task>
这篇关于如何创建Task类型的新Task?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文