Search

Atalasoft Knowledge Base

INFO: Avoiding Memory Leaks and AccessViolationException with AbbyyEngine by using STAThread

Administrator
DotImage

NOTE: This article discusses a single aspect of the AbbyyEngine: for a more generalized overview please see
INFO: AbbyyEngine - Overview

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:

Abbyy KB: Using the 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.

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.

Code Snippet to Mark an Entry-point With STAThread Attribute

using System;

namespace Demo
{
    public static class Program 
    {
        [STAThread]
        public static void Main(params string[] args)
        {

        }
    }
}

Code Snippet to Create an STA Thread

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);
            thread.SetApartmentState(ApartmentState.STA);

            //Other thread setup staff like making it background or not, set priority or culture settings.
            //thread.IsBackground = true;
            //thread.CurrentCulture = new CultureInfo("ru-ru");
            //etc.

            return thread;
        }
   }
}

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

Additional Resource Materials / Related Articles

INFO:AbbyyEngine - Overview

MS KB: Understanding and Using COM Threading Models

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 Article:

Q10465 - INFO: Avoiding Memory Leaks and AccessViolationException with AbbyyEngine by using STAThread

Details
Last Modified: Last Month
Last Modified By: Tananda
Type: INFO
Rated 5 stars based on 1 vote
Article has been viewed 81 times.
Options
Also In This Category