BlockingCollection OperationCanceledException

时间:2014-07-24 10:48:01

标签: c# multithreading parallel-processing task

我们在工作中获得了这段代码,我们从后台线程中的BlockingCollection读取报告进度。线路偶尔

foreach (int i in collection.GetConsumingEnumerable())

将抛出OperationCancelledException。这看起来很不寻常,因为看不到取消令牌。事实上,正如ObjectDisposedException方法的文档中提到的那样,我期待GetConsmingEnumerable。有谁知道发生了什么?它偶尔会发生。

class Program
{
    public static void Process()
    {
        var collection = new System.Collections.Concurrent.BlockingCollection<int>();

        Task.Factory.StartNew(() =>
        {
            foreach (int i in collection.GetConsumingEnumerable())
            {                    
                Console.WriteLine(i); // simulate reporting progress
            }
        }, TaskCreationOptions.LongRunning);

        var input = Enumerable.Range(1, 100); // simulate list of items to do work on

        Parallel.ForEach(input, i =>
        {
            Thread.Sleep(100); // Simulate doing work

            collection.Add(i);                
        });

        collection.CompleteAdding();
    }

    static void Main(string[] args)
    {
        Process();

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        Console.ReadKey();
    }
}

0 个答案:

没有答案