C# Task.Delay 简单测试
原创
©著作权归作者所有:来自51CTO博客作者覺醒的原创作品,请联系作者获取转载授权,否则将追究法律责任
class TaskDelayTest
{
Stopwatch sw = new Stopwatch();
public void DoRun()
{
Console.WriteLine($"Caller:Before call.");
ShowDelayAsync();
//ShowDelay();
Console.WriteLine($"Caller:After call.");
}
private async void ShowDelayAsync()
{
sw.Start();
Console.WriteLine($" 延时前:{sw.ElapsedMilliseconds}");
await Task.Delay(1000); // 不会阻塞当前线程
Console.WriteLine($" 延时后:{sw.ElapsedMilliseconds}");
}
private async void ShowDelay()
{
sw.Start();
Console.WriteLine($" 延时前:{sw.ElapsedMilliseconds}");
await Task.Run(()=> Thread.Sleep(1000));
Console.WriteLine($" 延时后:{sw.ElapsedMilliseconds}");
}
}
class Program
{
static void Main()
{
TaskDelayTest test = new TaskDelayTest();
test.DoRun();
Console.ReadKey();
}
}
输出:
Caller:Before call.
延时前:0
Caller:After call.
延时后:1027
参考:
《图解教程》