In ImageGear, why am I running into AccessViolationExceptions when I run my application in parallel?

Question

In ImageGear, why am I running into AccessViolationExceptions when I run my application in parallel?

Answer

This issue can sometimes occur if ImGearPDF is being initialized earlier in the application. In order to use ImGearPDF in a multi-threaded program, it needs to be initialized on a per-thread basis. For example, if you have something like this:

ImGearPDF.Initialize();
Parallel.For(...)
{ 
    // OCR code
}
ImGearPDF.Terminate();

Change it to this:

Parallel.For(...)
{
    ImGearPDF.Initialize();
    // OCR code
    ImGearPDF.Terminate();
}

The same logic applies to other ImageGear classes, such as ImGearPage instances or the ImGearRecognition class – you should create one instance of each class per thread, rather than creating a single instance and accessing it across threads. In the case of the ImGearRecognition class, you’ll have to use the createUnique parameter to make that possible e.g.:

ImGearRecognition recEngine = ImGearRecognition(true);

instead of

ImGearRecognition recEngine = ImGearRecognition();