I need an advice on multithreading implementation in WinForms C# application. We have an image – with text and numbers and there are separate methods to 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 the result, whole proccess takes approximately 1 second.
I was thinking about running OCR on different threads, simultaneously. For that 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 was not getting any results..
so is it possible to implemet multithreading in my case? Which approach do I have to use?
- task factory
- background worker
- threads
- 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 example).
Edit:
seems like
textBox1.Text = "" + text[0];
was executed faster than
string[] text;
Task.Factory.StartNew(() =>
{text = getText(bitmap, dictionary2);});
that’s why TextBox field 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 do not make any difference.. I’m getting the same speed test result without them.
You’re starting tasks correctly, but you’re never waiting for them to finish. What you want to do is something similar to;
More example code can be found here.
Alternately, you can return the value from the task instead of assigning it to a variable and use Task.Result which when you access it will wait for the task to finish and return the result of the Task.