异步和等待不起作用 [英] async and await are not working
问题描述
我正在尝试学习.NET 4.5的异步和等待功能.首先,这是我的代码
I am trying to learn the async and await features of .NET 4.5 .First of all here's my code
static async void Method()
{
await Task.Run(new Action(DoSomeProcess));
Console.WriteLine("All Methods have been executed");
}
static void DoSomeProcess()
{
System.Threading.Thread.Sleep(3000);
}
static void Main(string[] args)
{
Method();
//Console.WriteLine("Method Started");
Console.ReadKey();
}
此代码在控制台上没有给我任何结果.我不明白为什么.我的意思是不是任务应该只是没有阻塞的线程.但是,如果我在主要方法中取消注释Console.WriteLine(),一切似乎都可以正常工作.
This code doesn't give me any results on the console. I cant understand why. I mean aren't tasks suppose be just threads that aren't blocking. However if i uncomment the Console.WriteLine() in the main method everything seems to be working fine.
有人可以告诉我这是怎么回事吗?
Can anybody tell me what's going on here ?
推荐答案
在异步/等待模式下,某些事情与以前的线程有所不同.
With the async/await pattern some things are different as previously with threads.
-
您不应使用
System.Threading.Thread.Sleep
因为这仍然会阻塞并且不适用于异步. 而是使用Task.Delay
you shouldn't use
System.Threading.Thread.Sleep
because this is still blocking and does not work with async. Instead useTask.Delay
考虑使所有代码异步.只有控制台中的Main方法不能与原因不同步
Consider making all your code async. Only the Main method in your console cannot be async of cause
避免使用async void
方法.基本上,异步void仅用于无法返回内容的事件处理程序.所有其他异步方法应返回Task
或Task<T>
Avoid async void
methods. Basically async void is just meant for event handlers which cannot return something. All other async methods should return Task
or Task<T>
修改您的示例:
static async Task Method()
{
await DoSomeProcess();
Console.WriteLine("All Methods have been executed");
}
static async Task DoSomeProcess()
{
await Task.Delay(3000);
}
现在更改您的Main方法,因为这应该是您开始任务的地方
Now change your Main method because this should be the place where you start your task
Task.Run(() => Method()).Wait();
//Console.WriteLine("Method Started");
Console.ReadKey();
这篇关于异步和等待不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!