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();
} async Task PutTaskDelay()
{
await Task.Delay(, 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(, 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

 
 

Thread.Sleep vs. Task.Delay的更多相关文章

  1. Task.Delay() 和 Thread.Sleep() 区别

    1.Thread.Sleep 是同步延迟,Task.Delay异步延迟. 2.Thread.Sleep 会阻塞线程,Task.Delay不会. 3.Thread.Sleep不能取消,Task.Dela ...

  2. Thread.Sleep(1000) 、Task.Delay(1000).Wait() 区别

    public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken){    if (millise ...

  3. Task C# 多线程和异步模型 TPL模型 【C#】43. TPL基础——Task初步 22 C# 第十八章 TPL 并行编程 TPL 和传统 .NET 异步编程一 Task.Delay() 和 Thread.Sleep() 区别

    Task C# 多线程和异步模型 TPL模型   Task,异步,多线程简单总结 1,如何把一个异步封装为Task异步 Task.Factory.FromAsync 对老的一些异步模型封装为Task ...

  4. task.delay 和 thread.sleep

    1.Thread.Sleep 是同步延迟. Task.Delay异步延迟. 2.Thread.Sleep 会阻塞线程,Task.Delay不会. 3.Thread.Sleep不能取消,Task.Del ...

  5. .Net4.0如何实现.NET4.5中的Task.Run及Task.Delay方法

    前言 .NET4.0下是没有Task.Run及Task.Delay方法的,而.NET4.5已经实现,对于还在使用.NET4.0的同学来说,如何在.NET4.0下实现这两个方法呢? 在.NET4.0下, ...

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

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

  7. C#异步延迟Task.Delay

    一. 1.Task.Delay实质是创建一个任务,再任务中开启一个定时间,然后延时指定的时间2.Task.Delay不和await一起使用情况,当代码遇到Task.Delay一句时,创建了了一个新的任 ...

  8. Thread.Join 和 Task.Wait 方法

    这两个方法 可以说是类似的功能,都是对当前任务进行等待阻塞,执行完毕后再进行后续处理 talk is cheap, show you code,下面一个是异步执行,一个是加了阻塞,可以对比不同执行结果 ...

  9. Task.Delay方法的2个应用实例,单元测试等待,限时限次下载远程资源

    如果想让程序异步等待一段时间,可以考虑使用Task.Delay方法. 比如,在单元测试中模拟一个异步操作. static async Task<T> DelayedResult<T& ...

随机推荐

  1. 表达式拼接Expression<Func<IEntityMapper, bool>> predicate

    /// <summary> /// 重写以筛选出当前上下文的实体映射信息 /// </summary> protected override IEnumerable<IE ...

  2. AutoMapper不用任何配置就可以从dynamic(动态)对象映射或映射到dynamic对象。

    http://www.cnblogs.com/farb/p/4934476.html#pz

  3. sqlmap注入小结

    sqlmap注入时: 1.判断可注入的参数 2.判断可以用那种SQL注入技术来注入 3.识别出哪种数据库 4.根据用户选择,读取哪些数据 sqlmap支持五种不同的注入模式: 1.基于布尔的盲注,即可 ...

  4. ActionScript学习笔记

    ActionScript学习笔记 ActionScript中预定义的数据类型:Boolean.int.Number.String.uint 其中,int.Number.uint是处理数字的.int用来 ...

  5. 再说linux中的rm mv 遍历执行多个文件的操作: find + xagrs

    参考文章: http://cfqtyaogang.blog.163.com/blog/static/218051022011812111342203/, 这篇文章讲得很全面很详细... 包括不好理解的 ...

  6. Highcharts X轴名称太长,如何设置下面这种样式

      Highcharts所有的图表除了饼图都有X轴和Y轴,默认情况下,x轴显示在图表的底部,y轴显示在左侧(多个y轴时可以是显示在左右两侧),通过chart.inverted = true 可以让x, ...

  7. 解决python3 UnicodeEncodeError: 'gbk' codec can't encode character '\xXX' in position XX

    从网上抓了一些字节流,想打印出来结果发生了一下错误: UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position ...

  8. mysql 总结二(自定义函数)

    本质:mysql内置函数的一种扩展,本质上与mysql内置函数一样. 函数必要条件: @1:参数(非必备): @2:返回值: 模板: create function function_name ret ...

  9. hdu.1104.Remainder(mod && ‘%’ 的区别 && 数论(k*m))

    Remainder Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total ...

  10. MySQL源码分析以及目录结构

    原文地址:MySQL源码分析以及目录结构作者:jacky民工 主要模块及数据流经过多年的发展,mysql的主要模块已经稳定,基本不会有大的修改.本文将对MySQL的整体架构及重要目录进行讲述. 源码结 ...