如何让我的程序无限循环下面的方法,并在20-30秒后不退出以下消息:A first chance exception of type 'System.Threading.Tasks.TaskCanceledException' occurred in mscorlib.dll
。
private static void Main()
{
using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
{
Task task = GenerateBids(cancellationTokenSource.Token);
task.Wait(cancellationTokenSource.Token);
}
}
private static async Task GenerateBids(CancellationToken cancel)
{
while (!cancel.IsCancellationRequested)
{
try
{
for (int x = 0; x < 4; x++)
MethodA();
await Task.Delay(2000, cancel);
if (cancel.IsCancellationRequested)
return;
MethodB();
MethodC();
MethodD();
await Task.Delay(2000, cancel);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
答案 0 :(得分:1)
而不是
task.Wait(cancellationTokenSource.Token);
写
task.Wait();
否则30秒后对Wait
的调用将被取消此异常......