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. linux win 通用的获取Mac的方法

    经测试下面方法获取Mac跨平台 protected override void OnLoad(EventArgs e) { Response.Write(string.Join("<b ...

  2. Node.js Tools 1.2 for Visual Studio 2015 released

    https://blogs.msdn.microsoft.com/visualstudio/2016/07/28/node-js-tools-1-2-visual-studio-2015/ What ...

  3. 使用EntityFramework6.1的DbCommandInterceptor拦截生成的SQL语句

    开始 EF6.1也出来不少日子了,6.1相比6.0有个很大的特点就是新增了System.Data.Entity.Infrastructure.Interception 命名空间,此命名空间下的对象可以 ...

  4. 在VS2013中强制IIS Express应用程序池使用经典模式

    直接在文件夹地址栏输入 %userprofile%\documents\iisexpress\config\applicationhost.config 会打开上边的配置文件 将 <siteDe ...

  5. asp.net mvc @Html.Partial @Html.Action @Html.RenderPartial @Html.RenderAction区别

    转载自 :  <asp.net mvc @Html.Partial @Html.Action @Html.RenderPartial @Html.RenderAction区别> 先复制过来 ...

  6. css sprite

    1.What? CSS Sprites其实就是把网页中一些背景图片整合到一张图片文件中,再利用CSS的“background-image”,“background- repeat”,“backgrou ...

  7. Myeclipse中的web项目审查(jquery-2.1.1.min.js)出现错误

    前言,本来在把web项目搞得好看一些,从网上下载了一个很炫酷的模板导入web中,无奈出现了错误,如下:

  8. 给select添加自定义值和选项

    添加选项: document.getElementById("id_select").options.add(new Option("name", " ...

  9. 网站SEO优化之添加Sitemap文件。

    Sitemap.xml 故名思意就是站点地图文件,可以指引Google spider 收录相应网页.正确地使用Google Sitemap,可以确保让Google spider 不遗漏网站内的任何页面 ...

  10. 数论只会GCD。。。

    一些关于GCD的代码.... #include <iostream> #include <cstdio> #include <cstring> using name ...