猿问

如何在C#4.0中使任务进入睡眠状态(或延迟)?

.NET 4.5中 有Task.Delay


在.NET 4.0中我该如何做?


动漫人物
浏览 603回答 2
2回答

尚方宝剑之说

您可以使用在4.0中Timer创建Delay方法:public static Task Delay(double milliseconds){&nbsp; &nbsp; var tcs = new TaskCompletionSource<bool>();&nbsp; &nbsp; System.Timers.Timer timer = new System.Timers.Timer();&nbsp; &nbsp; timer.Elapsed+=(obj, args) =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; tcs.TrySetResult(true);&nbsp; &nbsp; };&nbsp; &nbsp; timer.Interval = milliseconds;&nbsp; &nbsp; timer.AutoReset = false;&nbsp; &nbsp; timer.Start();&nbsp; &nbsp; return tcs.Task;}
随时随地看视频慕课网APP
我要回答