Thread.Sleep与Task.Delay的区别
Thread.Sleep与Task.Delay的区别1、Thread.Sleep 是同步延迟,Task.Delay异步延迟。
2、Thread.Sleep 会阻塞线程,Task.Delay不会。
3、Thread.Sleep不能取消,Task.Delay可以。
4、Thread.Sleep实例
(1)、代码
using System
using System.Threading;
namespace ThreadTest
{
public class A
{
public static void B()
{
while (true)
{
Console.WriteLine("A.B is running in its own thread.");
}
}
}
public class C
{
public static void Main()
{
Thread t = new Thread(new ThreadStart(A.B));
t.Start();
Thread.Sleep(5);
t.Abort();
t.Join();
Console.WriteLine("A.B has finished");
Console.ReadLine();
}
}
}
(2)、运行后显示若干行"A.B is running in its own thread."和一行"A.B has finished";
(3)、若取消程序中的“Thread.Sleep(5);”句,则运行后只显示"A.B has finished"。
5、Task.Delay()实例
// Thread.Sleep是同步延迟, Task.Delay异步延迟;
// Thread.Sleep不能取消,Task.Delay可以。
Task.Run(async () =>
{
//将任务延迟1000毫秒后运行,如果无限等待那么指定为-1
await Task.Delay(1000);
Console.WriteLine("Task Start");
//CancellationToken设置为true就是标志Task任务取消,为false和 await Task.Delay(1000)一样将任务延迟3000毫秒后运行
await Task.Delay(1000, new CancellationToken(true));
Console.WriteLine("这里不会被执行,因为任务取消了~");
});