[HttpGet] public async Task<string> TestUU() { ParentTsk().Wait(); Console.WriteLine("Hello World!"); return "ok"; }
public async static Task ParentTsk() { CancellationTokenSource cts = new CancellationTokenSource(); cts.CancelAfter(20); Task<string> workTsk = Task.Run(async () => await WorkTsk()); Task<string> watchTsk = Task.Run(async () => await WatchTsk(cts.Token)); Task<string>[] tskArray = new Task<string>[] { watchTsk, workTsk }; var rsltTsk = await Task.WhenAny(tskArray); Console.WriteLine($"执行结果{rsltTsk.Result}"); }
public async static Task<string> WorkTsk() { string fileName = @"d:\tstFile.txt"; List<int> lstINt = Enumerable.Range(0, 5000).ToList(); foreach (var item in lstINt) { await System.IO.File.AppendAllTextAsync(fileName, $"{item}|"); } return "it is WorkTsk"; } public async static Task<string> WatchTsk(CancellationToken token) { while (!token.IsCancellationRequested) { await Task.Delay(10); } return "it is WatchTsk"; }
方案二:父子线程
标签:Task,C#,await,static,WatchTsk,退出,async,超时,public From: https://www.cnblogs.com/OneSeting/p/17510430.html