方法一:
利用Task.WhenAny
namespace ConsoleApp1 { internal class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); CancellationTokenSource cts = new CancellationTokenSource(); Task taskMethod1 = Method1(cts.Token); Task taskComplete = Task.WhenAny(taskMethod1, Task.Delay(100, cts.Token)); if (taskComplete != taskMethod1) //超时 { cts.Cancel(); } Console.WriteLine("end"); Console.ReadLine(); } public static async Task Method1(CancellationToken token) { Console.WriteLine("Method1 start"); await Task.Delay(1000, token); Console.WriteLine("Method1 end"); } public static async Task Method2(CancellationToken token) { await Task.Delay(2000, token); Console.WriteLine("Method2"); } } }
方法二:
.WaitAsync
namespace ConsoleApp1 { internal class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); Demo(); Console.WriteLine("end"); Console.ReadLine(); } public static async Task Demo() { CancellationTokenSource cts = new CancellationTokenSource(); try { await Method2(cts.Token).WaitAsync(TimeSpan.FromSeconds(1)); } catch (Exception ex) { Console.WriteLine("timeout"); cts.Cancel(); } } public static async Task Method1(CancellationToken token) { Console.WriteLine("Method1 start"); await Task.Delay(1000, token); Console.WriteLine("Method1 end"); } public static async Task Method2(CancellationToken token) { try { await Task.Delay(5000, token); Console.WriteLine("Method2"); } catch (Exception ex) { Console.WriteLine($"{ex.Message}"); } } public static async Task Method3() { await Task.Delay(2000); Console.WriteLine("Method2"); } } }
标签:core,Task,Console,异步,Method1,token,static,WriteLine,net From: https://www.cnblogs.com/cxxtreasure/p/17899174.html