We use both Thread.Sleep() and Task.Delay() to suspend the execution of a program for some given time. But are we actually suspending the execution? What is the difference between these two? How to abort from a Sleeping thread or from a delaying task. Those are some of the questions I believe most of us have. Hopefully I am trying to answer all the questions above.
Let’s go by an example. I have a very simple windows forms application which has the following form.
I have the following two basic helper methods and I am calling these two methods from my “Thread Sleep” and “Task Delay” button.
void PutThreadSleep()
{Thread.Sleep(5000);
}async Task PutTaskDelay()
{await Task.Delay(5000, tokenSource.Token);
} private void btnThreadSleep_Click(object sender, EventArgs e)
{PutThreadSleep();MessageBox.Show("I am back");
} private async void btnTaskDelay_Click(object sender, EventArgs e)
{await PutTaskDelay();MessageBox.Show("I am back");
}

asically there is nothing to describe about the code up there (I am not going to explain what async and await here, you can find many articles in MSDN and one of my previous post explaining async/await). When I clicked both these buttons, the message boxes will be displayed after 5 seconds. But there are significant differences between these two ways. Let’s find out what.

Thread.Sleep()

This is the classical way of suspending a execution. This method will suspend the current thread until the elapse of giving time.When you put the Thread.Sleep in the above way, there is nothing you can do to abort this except by waiting till the time elapses or by restarting the application. That’s because this suspends the main thread the program is running. And because of that the UI is not responsive.

Task.Delay()

When comparing to Thread.Sleep(), Task.Delay() acts in a different way. Basically Task.Delay() will create a task which will complete after a time delay. This task will be running in a different thread, UI is responsive, and that's because Task.Delay() is not blocking the main thread.
Behind the scene what is happening is there is a timer ticking till the specified time. Since there is a timer, anytime we can cancel the task delay by stopping the timer. To cancel, I am modifying the above PutTaskDelay() method as follows.
CancellationTokenSource tokenSource = new CancellationTokenSource(); async Task PutTaskDelay()
{ try{await Task.Delay(5000, tokenSource.Token);}catch (TaskCanceledException ex){}catch (Exception ex){ }
}

Here when the task got cancelled, it will be throwing me a TaskCanceledException. I am just catching the exception and suppressing it, because  don't want to show any message about that.

So in my “Cancel Task Delay” button click event, I am asking the task to be cancelled.

private void btnCancelTaskDelay_Click(object sender, EventArgs e)
{tokenSource.Cancel();
}

Once the task has been cancelled, the control returns immediately to the next line and message box will be shown.

https://code.msdn.microsoft.com/ThreadSleep-vs-TaskDelay-766b46b7

转载于:https://www.cnblogs.com/LittleFeiHu/p/4542631.html

Thread.Sleep vs. Task.Delay相关推荐

  1. 什么时候使用Task.Delay,什么时候使用Thread.Sleep?

    本文翻译自:When to use Task.Delay, when to use Thread.Sleep? Are there good rule(s) for when to use Task. ...

  2. 15.3 Task Task.Yield和Task.Delay说明

    https://blog.csdn.net/hurrycxd/article/details/79827958 书上看到一个Task.Yield例子,Task.Yield方法创建一个立即返回的awai ...

  3. Task.Delay()方法

    Task.Delay方法只会延缓异步方法中后续部分执行时间,当程序执行到await表达时,一方面会立即返回调用方法,执行调用方法中的剩余部分,这一部分程序的执行不会延长.另一方面根据Delay()方法 ...

  4. Thread\Threading.Timer\Task中ShowDialog()方法报错:“在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式”

    在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式.请确保您的 Main 函数带有 STAThreadAttribute 标记. 出错环境: 1.在Thread线程中,调用Show ...

  5. C# 异步与Windows应用程序

    把 async 关键字用于 UWP 应用程序,需要注意,在 UI 线程中调用 await 之后,当异步方法返回时,将默认返回到 UI 线程中.这便于在异步方法完成后更新 UI 元素. 注意 为了创建 ...

  6. 如何使用 dotTrace 来诊断 netcore 应用的性能问题

    最近在为 Newbe.Claptrap 做性能升级,因此将过程中使用到的 dotTrace 软件的基础用法介绍给各位开发者. Newbe.Claptrap 是一个用于轻松应对并发问题的分布式开发框架. ...

  7. 异步编程中的最佳做法(Async/Await) --转

    近日来,涌现了许多关于 Microsoft .NET Framework 4.5 中新增了对 async 和 await 支持的信息. 本文旨在作为学习异步编程的"第二步":我假设 ...

  8. 【转】2.2[译]async/await中阻塞死锁

    这篇博文主要是讲解在async/await中使用阻塞式代码导致死锁的问题,以及如何避免出现这种死锁.内容主要是从作者Stephen Cleary的两篇博文中翻译过来. 原文1:Don'tBlock o ...

  9. SQLite数据库database is locked解决

    开发语言C# 主要通过配置数据库连接字符串解决 关键语句:Journal Mode=WAL: /// <summary> /// 数据库连接字符串 /// </summary> ...

最新文章

  1. 钉钉 6.0 盯上应用开发
  2. 398. Random Pick Index
  3. 8086的内存分段机制
  4. 【百家稷学】计算机视觉典型实践(珠海格力电器技术分享)
  5. django中使用POST方法 获取POST数据
  6. java内存shell_Springboot 内存shell
  7. 二级c语言上机程序填空,浙江省计算机二级c语言上机考试真题(二)程序填空
  8. 同一个html自动跳转分页,一个页面有多个分页,相互影响
  9. 也乱弹Book.Save而引OO对话
  10. oracle怎么装测试库,测试库csdb安装ORACLE_TEXT组件
  11. android图标分组名称唯美,手机屏幕分组好听名字
  12. 计算机专业实践报告立题依据,论文的选题依据.doc
  13. 如何查找一篇论文的源代码
  14. Fate Decision剧本
  15. pytorch实现bnn
  16. Mac SecureCRT Toolbar 的图标很大很丑是不是?
  17. 新晋流量操盘手(一行) 探索百度贴吧高阶引流玩法
  18. 张建宁老师主讲:计算机网络基础(笔记)
  19. android 如何去获取手机Gps的信号强度
  20. Windows 10 20H1 2004新功能

热门文章

  1. 区块链学习笔记(3)--交易机制与双花
  2. 联想便携式计算机720s使用什么硬盘盒,8代酷睿加持!联想720S轻薄本评测
  3. 硬件系列(五)-------------Android小票打印机连接 (已封装好,可直接使用)
  4. 好用到爆炸的Chrome谷歌插件下载——妈妈再也不用担心我找不到好的插件了
  5. JS中attr 和 prop 的区别
  6. SRP简介(SRP--Single-Responsibility Principle):
  7. linux --- linux目录结构
  8. N沟道的Vgs是正的,P沟道的Vgs是负的
  9. 201421410013 唐昭靖 作业1
  10. Fabric-ca与现有fabric网络组织绑定