【发布时间】:2015-09-05 01:12:27
【问题描述】:
谁能解释一下为什么下面的 public async Task DoStuff() 方法仍然可以工作而不返回任何东西?它没有说 void,所以我假设返回类型必须是 Task。
当我从 DoStuff() 方法中删除 async 和 await 关键字时,编译器会给我一个 "not all代码路径返回值” 错误。但是,如果我添加 async 和 await 关键字,它似乎不需要返回类型,尽管方法签名中缺少 void 关键字。没看懂!
究竟什么是任务?微软解释得很糟糕。谢谢。
namespace Async_and_Await_Example
{
class Program
{
static void Main(string[] args)
{
AsyncAwaitDemo demo = new AsyncAwaitDemo();
demo.DoStuff();
for (int i = 0; i < 100; i++)
{
Console.WriteLine("Working on the Main Thread...................");
}
}
}
public class AsyncAwaitDemo
{
public async Task DoStuff()
{
await Task.Run(() =>
{
CountToFifty();
});
}
private static async Task<string> CountToFifty()
{
int counter;
for (counter = 0; counter < 51; counter++)
{
Console.WriteLine("BG thread: " + counter);
}
return "Counter = " + counter;
}
}
}
【问题讨论】:
标签: c# .net asynchronous async-await task