实现.net 4.0的异步方法
.net 4.5以上有Task.Run和Task.Delay。
.net 4.0没有可以使用以下代码实现:
class TaskEx
{
public static Task Run(Action action)
{
var tcs = new TaskCompletionSource<object>();
new Thread(() => {
try
{
action();
tcs.SetResult(null);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
}){ IsBackground = true }.Start();
return tcs.Task;
}
public static Task<TResult> Run<TResult>(Func<TResult> function)
{
var tcs = new TaskCompletionSource<TResult>();
new Thread(() =>
{
try
{
tcs.SetResult(function());
}
catch (Exception ex)
{
tcs.SetException(ex);
}
})
{ IsBackground = true }.Start();
return tcs.Task;
}
public static Task Delay(int milliseconds)
{
var tcs = new TaskCompletionSource<object>();
var timer = new System.Timers.Timer(milliseconds) { AutoReset = false };
timer.Elapsed += delegate { timer.Dispose();tcs.SetResult(null); };
timer.Start();
return tcs.Task;
}
}
}
使用方法:
TaskEx.Run(() =>
{
Thread.Sleep(5000);
Console.WriteLine("Just For Test.");
});
//Task.Run<TResult>(Func<TResult> function)方法
string result = TaskEx.Run(() =>
{
Thread.Sleep(5000);
return "Just For Test.";
}).Result;
Console.WriteLine(result);
//Task.Delay(int milliSeconds)方法
TaskEx.Delay(5000).Wait();