我正在尝试在带有 VS2012 框架 4.5 的表单上使用 async 和 await 命令。我的异步方法 SlowMethodAsync 不返回任何内容。请注意,此代码在控制台应用程序中运行良好。
private void button1_Click(object sender, EventArgs e)
{
var task = SlowMethodAsync();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
System.Threading.Tasks.TaskStatus status = task.Status;
Console.WriteLine("Slow method result on Thread: {0}", task.Result); //This line never executes
Console.WriteLine("Main complete on {0}", Thread.CurrentThread.ManagedThreadId);
}
//Why is this method not returning anything?
static async Task<int> SlowMethodAsync()
{
Console.WriteLine("Slow method started on Thread: {0}", Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000);
Console.WriteLine("Slow method complete on Thread: {0}", Thread.CurrentThread.ManagedThreadId);
return 42;
}