C# Task Delay 使用
方法一:
public static System.Threading.Tasks.Task Delay (int millisecondsDelay, System.Threading.CancellationToken cancellationToken);
创建可取消的任务,该任务在指定的毫秒数后完成。
using System; using System.Threading; using System.Threading.Tasks; public class Example { public static void Main() { CancellationTokenSource source = new CancellationTokenSource(); var t = Task.Run(async delegate { await Task.Delay(1000, source.Token); return 42; }); source.Cancel(); try { t.Wait(); } catch (AggregateException ae) { foreach (var e in ae.InnerExceptions) Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message); } Console.Write("Task t Status: {0}", t.Status); if (t.Status == TaskStatus.RanToCompletion) Console.Write(", Result: {0}", t.Result); source.Dispose(); } }
方法二:
public static System.Threading.Tasks.Task Delay (int millisecondsDelay);
创建一个任务,该任务在指定的毫秒数后完成。
public class Example { public static void Main() { var t = Task.Run(async delegate { await Task.Delay(1000); return 42; }); t.Wait(); Console.WriteLine("Task t Status: {0}, Result: {1}", t.Status, t.Result); } }