I find it difficult to answer this question to make the answer helpful.
I'll try to put it in this way: this attempt to design multithreading code failed. Please, do your favor and don't try to improve it. You will need abandon it and start writing correct code from scratch, but to help you I would need to know what should be accomplished and why.
For now, I can only explain what's wrong and give you some references which could give your better ides.
The main problem is your attempt to synchronize thread using home-baked method based on spin wait. If you think that you can use non-threading techniques and apply them to thread, think again. You fail to use thread synchronization primitives which cannot be implemented not using OS calls, by combination of "if" "while" and the like. When you wait for system events, OS switches your thread off and keeps it in a special wait state and never schedule it back to execution until waken up, so the thread uses strictly zero CPU time. You simply keep the thread running waiting for a regular condition. This is not multithreading. The closest multithreading analog of such wait is
EventWaitHandle
.
One such bad thing is
Application.DoEvents
. By some reason, this is a common fallacy. You should never use it, as a matter of thumb rule. As to waiting for
DoEvents
in another thread, this is a way to wait forever, as you can keep pumping messages the way they never end.
Each and every
Sleep
call makes no sense. You sleep 10 ms; why? Do you hope something will change.
One more bad sign is identification of threads by
ManagedThreadId
. Why? There is no need to do this. Another bad sign is changing thread priority. You really never need it. If your logic is wrong, priority cannot improve thing. Think about it. By raising priority you don't make anything faster, you only make other threads yielding to you thread more often. Why do you think it improves throughput?
You code looks too complex for the task. This is one reason I cannot understand the purpose of all this. If would be possible if it was almost working code with just one or two problems. In this case, nearly everything is wrong. So, I cannot help you with your code. Again, I am sure you should start it over.
Just few ideas.
To work with UI, you never call any UI methods or properties from non-UI thread. You cannot call anything related to UI from non-UI thread. Instead, you need to use the method
Invoke
or
BeginInvoke
of
System.Windows.Threading.Dispatcher
(for both Forms or WPF) or
System.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[
^],
Control events not firing after enable disable + multithreading[
^].
—SA