Using multithreading to perform OCR with C #

I need some advice on implementing multithreading in a C # WinForms application. We have an image - with text and numbers , and there are separate methods for OCR different types of data . For example:

decimal[] numbers = getNumbers(bitmap, dictionary1);
string[] text = getText(bitmap, dictionary2);
int[] integers = getInts(bitmap, dictionary3);
// add 5 more data types (list, int[], etc..)


As a result, the entire process takes approximately 1 second.

I was thinking about managing OCR on different streams at the same time. For this reason, I tried to use Task Factory:

decimal[] numbers;
Task.Factory.StartNew(() =>
{numbers = getNumbers(bitmap, dictionary1);});
string[] text;
Task.Factory.StartNew(() =>
{text = getText(bitmap, dictionary2);});
textBox1.Text = "" + text[0]; // nothing


but I didn't get any results.

so is it possible to implement multithreading in my case? Which approach should I use?

  • factory task
  • background worker
  • Topics
  • or something else?

If possible, can you give me a little advice on how to use your method, because TaskFactory failed when I tried to use it (as in the example).


it seems

textBox1.Text = "" + text[0];


ran faster than

string[] text;
Task.Factory.StartNew(() =>
{text = getText(bitmap, dictionary2);});


why the TextBox was empty .. so I moved "textBox1.Text =" "+ text [0];" at the very end of the code and finally got the result.

Edit 2:

ok, tasks don't matter. I am getting the same speed test result without them.


source to share

1 answer

You start tasks correctly, but you never wait for them to complete. What you want to do is like:

Task[] tasks = new Task[2];
decimal[] numbers;
tasks[0] = Task.Factory.StartNew(() =>
   {numbers = getNumbers(bitmap, dictionary1);});
string[] text;
tasks[1] = Task.Factory.StartNew(() =>
   {text = getText(bitmap, dictionary2);});

Task.WaitAll(tasks);  // Wait for all parallel tasks to finish 
                      // before using their output.

textBox1.Text = "" + text[0];


Additional example code can be found here .

Alternatively, you can return a value from the task instead of assigning it to a variable and use Task.Result , which, when accessing it, will wait for the task to complete and return the result of the task.



All Articles