c# Thread.Sleep与Task.Delay 区别
程序员文章站
2022-07-14 16:15:25
...
1、Thread.Sleep 是同步延迟, Task.Delay异步延迟。
2、Thread.Sleep 会阻塞线程,Task.Delay不会。
Task.Factory.StartNew(delegate
{
for(int i=1;i<50;i++)
{
System.Diagnostics.Debug.WriteLine(i.ToString());
Thread.Sleep(100);
}
});
Task.Factory.StartNew(delegate
{
for (int i = 101; i < 150; i++)
{
System.Diagnostics.Debug.WriteLine(i.ToString());
Task.Delay(100);
}
});
虽然此处delay的用法有待商榷,但确实不会阻塞
3、Thread.Sleep不能取消,Task.Delay可以。
引用别人的例子
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ThreadSleepTaskDelayDemo
{
public partial class Form1 : Form
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
public Form1()
{
InitializeComponent();
}
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");
}
void PutThreadSleep()
{
Thread.Sleep(5000);
}
async Task PutTaskDelay()
{
try
{
await Task.Delay(5000, tokenSource.Token);
}
catch (TaskCanceledException ex)
{
}
catch (Exception ex)
{
}
}
private void btnCancelTaskDelay_Click(object sender, EventArgs e)
{
tokenSource.Cancel();
}
}
}
上一篇: Linux挂载Windows共享文件夹
下一篇: Thread.sleep