有 Task.Delay 在.NET 4.5
There is Task.Delay in .NET 4.5
我怎样才能做到在.NET 4.0中的一样吗?
How can I do the same in .NET 4.0?
您可以使用定时器
来创建一个延迟
4.0的方法:
You can use a Timer
to create a Delay
method in 4.0:
public static Task Delay(double milliseconds)
{
var tcs = new TaskCompletionSource<bool>();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed+=(obj, args) =>
{
tcs.TrySetResult(true);
};
timer.Interval = milliseconds;
timer.AutoReset = false;
timer.Start();
return tcs.Task;
}