让程序无限循环,而不是退出System.Threading.Tasks.TaskCanceledException

时间:2015-03-12 23:11:24

标签: c# multithreading

如何让我的程序无限循环下面的方法,并在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);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

而不是

task.Wait(cancellationTokenSource.Token);

task.Wait();

否则30秒后对Wait的调用将被取消此异常......