Console.WriteLine(DateTime.Now);
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
CancellationToken stoppingToken = cancellationTokenSource.Token;
try
{
Task.Factory.StartNew(async () =>
{
Console.WriteLine("before");
await Task.Delay(Timeout.Infinite, stoppingToken);
Console.WriteLine("after");
}, stoppingToken, TaskCreationOptions.LongRunning, TaskScheduler.Current)
.Unwrap().Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine(DateTime.Now);
可根据实际情况将Wait改为 async await
网友评论