Document.Save() fails in multithreaded app with System.InvalidOperationException: Collection was modified; enumeration operation may not execute

Hi there,
When trying to iterate through two different documents page by page and saving each of the pages as an image to an MemoryStream, from time to time I get the following error:

Message:
Test method WordToPng.Tests.UnitTest1.CreateAsyncPngsFromDocs_OK threw exception:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

  Stack Trace: 

Enumerator.MoveNextRare()
Enumerator.MoveNext()
KU5.v(MU5 d)
KU5.d(MU5 d)
Document.d(Stream d, String v, SaveOptions c)
Document.Save(Stream stream, SaveOptions saveOptions)
Generator.CreateImageFromDocPage(Document doc, Int32 pageNumber) line 79
<>c__DisplayClass2_0.b__1() line 54
Task`1.InnerInvoke()
ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
— End of stack trace from previous location —
ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
— End of stack trace from previous location —
Generator.CompareTwoDocumentPagesAsync(Document doc1, Document doc2, Int32 pageNumber) line 56
<b__0>d.MoveNext() line 43
— End of stack trace from previous location —
Generator.GenerateAsync(String firstFilePath, String secondFilePath) line 47
UnitTest1.CreateAsyncPngsFromDocs_OK() line 15

The error occurs more often if the code is run under .NET 4.7.2 than under .NET Core 8.0.

Please find attached my solution → undner .Net 4.7.2, you might run the unit tests for 20 to 30 times for the error to occur, under .Net Core 8.0 up to 100 times until the error occurs.

Many thanks
WordToPng.zip (28.0 KB)

@tibitabi
We have opened the following new ticket(s) in our internal issue tracking system and will deliver their fixes according to the terms mentioned in Free Support Policies.

Issue ID(s): WORDSNET-27143

You can obtain Paid Support Services if you need support on a priority basis, along with the direct access to our Paid Support management team.

The issues you have found earlier (filed as WORDSNET-27143) have been fixed in this Aspose.Words for .NET 24.9 update also available on NuGet.

Thanks a lot! Looks good :slight_smile:

1 Like