【问题标题】:Collection was modified after the enumerator was instantiated error枚举器被实例化后,集合被修改错误
【发布时间】:2017-07-07 08:22:36
【问题描述】:

我正在尝试打印多个 PDF 字节数组。由于我需要允许用户同时打印多个报告的功能,因此我使用了 Parallel foreach。该函数很好地通过了第一个字节数组,但是在第二个 Dequeue 上,我得到“在枚举器被实例化后,集合被修改”。错误。如何在允许用户同时打印的同时解决此问题?

代码如下:

public static void PrintingQueue(Queue<byte[]> printQueue, string printer, int copies)
    {
        Parallel.ForEach(printQueue, (currentFile) =>
        {
            var printFile = printQueue.Dequeue();
            PrintWithGSPrint(printFile, printer, copies);

        });
    }

【问题讨论】:

    标签: c#


    【解决方案1】:

    试试这个解决方案:

    Parallel.ForEach 方法为队列中的每个项目提供了一个参数。在方法中使用该参数进行打印。然后在完成后清除队列。

    public static void PrintingQueue(Queue<byte[]> printQueue, string printer, int copies)
    {
        Parallel.ForEach(printQueue, (currentFile) =>
        {
            PrintWithGSPrint(currentFile, printer, copies);
        });
    
        printQueue.Clear();
    }
    

    【讨论】:

      【解决方案2】:

      例外是告诉你发生了什么。由于正在修改集合,foreach 语句无法正确执行。使用Dequeue 方法,您将从正在迭代的集合中删除一个项目。不要删除 foreach 循环中的项目,只需在完成任务后清理集合即可。

      https://msdn.microsoft.com/en-us/library/1c8bzx97(v=vs.110).aspx

      您可以做的另一件事是使用for 语句向后迭代您的集合。这样,如果必须,您将能够删除元素。您可以使用此答案查看如何向后迭代:https://stackoverflow.com/a/1582317/637840

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-06
        • 2022-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多