实现.net 4.0的异步方法
.net 4.5以上有Task.Run和Task.Delay。
.net 4.0没有可以使用以下代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
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; } } } |
使用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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(); |
如果您对C#游戏开发感兴趣,可以扫下面二维码加入我们的QQ群来一起学习交流
原创文章,转载请注明本文链接地址(违者必究):实现.net 4.0的异步方法