Task.Delay(1000) 和 Thread.Sleep(1000) 两个有文章吗?使用方面哪个优?各自使用于什么场景啊?
创建将在指定延迟后完成的任务,返回Task。可以通过await或 Task.Wait() 来达到 Thread.Sleep() 的效果。尽管,Task.Delay() 比 Thread.Sleep() 消耗更多的资源,但是Task.Delay()可用于为方法返回Task类型;或者根据CancellationToken取消标记动态取消等待。
Task.Delay()等待完成返回的Task状态为RanToCompletion;若被取消,返回的Task状态为Canceled。
public static void Test_Delay() { var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; Task.Factory.StartNew(() => { Thread.Sleep(1000); tokenSource.Cancel(); }); Console.WriteLine("taskDelay1"); Task taskDelay1 = Task.Delay(100000, token); try { taskDelay1.Wait(); } catch (AggregateException ae) { foreach (var v in ae.InnerExceptions) Console.WriteLine(ae.Message + " " + v.Message); } taskDelay1.ContinueWith((t) => Console.WriteLine(t.Status.ToString())); Thread.Sleep(100); Console.WriteLine(); Console.WriteLine("taskDelay2"); Task taskDelay2 = Task.Delay(1000); taskDelay2.ContinueWith((t) => Console.WriteLine(t.Status.ToString())); }
// 输出======================= // taskDelay1 // 发生一个或多个错误。 已取消一个任务。 // Canceled // // taskDelay2 // Completed
MSDN有说明不同:
private async void button1_Click(object sender, EventArgs e) { // Call the method that runs asynchronously. string result = await WaitAsynchronouslyAsync(); // Call the method that runs synchronously. //string result = await WaitSynchronously (); // Display the result. textBox1.Text += result; } // The following method runs asynchronously. The UI thread is not // blocked during the delay. You can move or resize the Form1 window // while Task.Delay is running. public async Task<string> WaitAsynchronouslyAsync() { await Task.Delay(10000); return "Finished"; } // The following method runs synchronously, despite the use of async. // You cannot move or resize the Form1 window while Thread.Sleep // is running because the UI thread is blocked. public async Task<string> WaitSynchronously() { // Add a using directive for System.Threading. Thread.Sleep(10000); return "Finished"; }
地址 :http://msdn.microsoft.com/en-us/library/vstudio/hh156528.aspx
就是说Thread.Sleep()会阻塞UI线程,而Task.Delay()不会。
msdn这个例子应该是await和没有await的区别。当然thread.sleep没有办法用await。