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. GIT@OSC中托管Android studio代码

    弄了好久,才知道如何向GIT@OSC托管代码,这里有需要的同学可以参考一下. 1.在GIT@OSC上新建一个工程 2.在AS中新建一个工程 3.在AS中选择“enable version contro ...

  2. group

    学习Linq时,经常会遇到Linq使用Group By问题,这里将介绍Linq使用Group By问题的解决方法. 1.计数 var q = from p in db.Products group p ...

  3. Lucene.Net+盘古分词->开发自己的搜索引擎

    //封装类 using System;using System.Collections.Generic;using System.Linq;using System.Web;using Lucene. ...

  4. Python之路【第七篇续】:进程、线程、协程

    Socket Server模块 SocketServer内部使用 IO多路复用 以及 “多线程” 和 “多进程” ,从而实现并发处理多个客户端请求的Socket服务端.即:每个客户端请求连接到服务器时 ...

  5. 在Linux主机上搭建SVN,用于同步提交修改,实现本地提交线上预览(SVN Hook功能实现)

    原文地址: http://blog.csdn.net/ROVAST/article/details/44887707?ref=myread 注:上文中钩子使用中有错误,正确的使用如下,上文中忘记了up ...

  6. Orchard源码分析(7.2):Controller相关

    概述 默认情况下,ASP.NET MVC内置的DefaultControllerFactory负责Controller实例的创建.Orchard定义了一个继承自DefaultControllerFac ...

  7. Python开发【第十七篇】:MySQL(一)

    一.概述 1.什么是数据库 ? 答:数据的仓库,如:在ATM的示例中我们创建了一个 db 目录,称其为数据库 2.什么是 MySQL.Oracle.SQLite.Access.MS SQL Serve ...

  8. step 3 socket

    socket 网络通讯三要素 IP地址(主机名) 网络中设备的标示 不易记忆,可以用主机名 本地回环地址:127.0.0.1 主机名:localhost 每台计算机都有一个 127.0.0.1 如果 ...

  9. dubbo框架----探索-大型系统架构设计(图解)

    对于高并发系统的架构要求: 1. 负载均衡 2.高并发 3.高可用 4.面向服务架构 (Dubbo框架使用) 5.分布式缓存 (redis分布式缓存) 6.分布式全文检索 (solr分分布式全文检索) ...

  10. bootstrap-dropdown

    功能:实现点击时下拉框显示 插件:dropdown.js 要点:dropdown功能往往用在导航栏.导航条上,用作标题显示.dropdown与<ul><li>标签搭配用. 以d ...