Avoiding Memory Leaks with AbbyyEngine by using STAThread

Jump to: navigation, search

DotImage provides an ability to perform OCR using the ABBYY engine (via our AbbyyEngine class). If you use this engine, then you should create, initialize, use and deinitialize it in a thread with a single-threaded apartment model, for additional info see the link: https://abbyy.technology/en:kb:faq:fre:engine_object

ABBYY doesn't guarantee the work of its engine it MTA-threads, for instance, the violation of this requirement can cause a memory leak or an AccessViolation error inside the engine.

Code / workaround

To set up the thread apartment model in C#, you need to mark your application entry-point method (usually it's the Main method) with STAThread attribute, OR, if you run an OCR operation in a separate thread, call the SetApartmentState method with ApartmentState.STA parameter before the separate thread run.

using System;

namespace Demo
    public static class Program  
        public static void Main(params string[] args)
             // your code here

Code snippet to mark an entry-point with STAThread attribute.

using System.Threading;
namespace Demo
    public class Utils
        // threadWorkDelegate is a function that doesn't accept parameters, or accept one parameter as 'object' type and has a 'void' return type
        // This function should create the ABBYY engine, process images and shutdown it.
        public static Thread CreateSTAThread(ThreadStart threadWorkDelegate)
            var thread = new Thread(threadWorkDelegate);
            //Other thread setup staff like making it background or not, set priority or culture settings.
            //thread.IsBackground = true;
            //thread.CurrentCulture = new CultureInfo("ru-ru");
            return thread;

For Visual Basic, the default apartment model is STA, so no additional actions required.

Additional Resource Materials / Related Articles

Q10432 - INFO: AbbyyEngine - Overview

Abbyy KB: Using the Engine object

ABBYY KB: Message "Attempted to read or write protected memory"

OCRSDK.com KB: The filename or extension is too long

Original Source Article

The original location for this article is
Q10465 - INFO: Avoiding Memory Leaks with AbbyyEngine by using STAThread