首页 新闻 会员 周边 捐助

Task.Delay(1000) 和 Thread.Sleep(1000) 两个有文章吗?使用方面哪个优?各自使用于什么场景啊?

0
悬赏园豆:20 [已关闭问题] 关闭于 2013-04-16 22:56

Task.Delay(1000) 和 Thread.Sleep(1000) 两个有文章吗?使用方面哪个优?各自使用于什么场景啊?

滴答的雨的主页 滴答的雨 | 老鸟四级 | 园豆:3660
提问于:2013-04-16 21:49
< >
分享
所有回答(2)
0

      创建将在指定延迟后完成的任务,返回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()));
        }
滴答的雨 | 园豆:3660 (老鸟四级) | 2013-04-16 22:56
// 输出=======================
// taskDelay1
// 发生一个或多个错误。 已取消一个任务。
// Canceled
// 
// taskDelay2
// Completed
支持(0) 反对(0) 滴答的雨 | 园豆:3660 (老鸟四级) | 2013-04-16 22:57
0

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

随风net | 园豆:189 (初学一级) | 2013-08-23 17:03

就是说Thread.Sleep()会阻塞UI线程,而Task.Delay()不会。

支持(0) 反对(1) 随风net | 园豆:189 (初学一级) | 2013-08-23 17:05

msdn这个例子应该是await和没有await的区别。当然thread.sleep没有办法用await。

支持(0) 反对(0) upcode-site | 园豆:200 (初学一级) | 2016-01-06 20:08
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册