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. msbuild FileSysExcludeFiles

    <?xml version="1.0" encoding="utf-8"?> <!-- This file is used by the pu ...

  2. java 正则 二次转义

    JAVA中的正则表达式"\\[([^\\]]+)\\]"这个表示什么意思?两个转义字符是为了表达什么? 正则表达式中"["这样的字符有特殊的意义,所以需要写成& ...

  3. css3实现渐变的iPhone滑动解锁效果

    先贴代码 <!DOCTYPE html> <html> <head> <style> p{ width:50%; margin:0 auto; line ...

  4. js jquery, jquery-ui 获取form各种表单input的值?

    如何获取? make up (for): 弥补, 补偿, her beaty cannot make up for her stu'pidity. five Basic laws of human s ...

  5. border边框的宽度/样式/颜色 全部值

    border 用emmet写border的时候, 缩写是:bd. 不是b, 也不是bdr: b会扩展成bottom, bdr 会扩展成 border-right, border的宽度: 1px 基本上 ...

  6. data and dream

    1 用通俗的语言介绍下线性回归->逻辑回归->SVM之间的区别和联系. 2 聚类算法的应用场景,以及k-means中的k值怎么确定. def center(data): center = ...

  7. PHP实现各种经典算法

    <?  //--------------------  // 基本数据结构算法 //--------------------  //二分查找(数组里查找某个元素)  function bin_s ...

  8. hdu1757 A Simple Math Problem

    Problem Description Lele now is thinking about a simple function f(x).If x < 10 f(x) = x.If x > ...

  9. 欧几里得证明$\sqrt{2}$是无理数

    选自<费马大定理:一个困惑了世间智者358年的谜>,有少许改动. 原译者:薛密 \(\sqrt{2}\)是无理数,即不能写成一个分数.欧几里得以反证法证明此结论.第一步是假定相反的事实是真 ...

  10. hdu.1430.魔板(bfs + 康托展开)

    魔板 Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submis ...