Reputation: 185
I have a bit of difficulty with multi-threading in C#.
I simply activate thread:
getMultiVarEnabled = true; Globals.readThread = new Thread(readMultipleVarForTextBoxes); Globals.readThread.IsBackground = true; Globals.readThread.Start();
Inside thread:
Globals.PIC.recievingMultiple = true; while (getMultiVarEnabled) // dodaj timeout { ... } Globals.PIC.recievingMultiple = false; Globals.readThread.Abort();
And to stop thread from main thread I use:
if (getMultiVarEnabled) { getMultiVarEnabled = false; while (Globals.PIC.recievingMultiple); Globals.readThread.Join(); Globals.readThread = null; }
The problem is that sometimes ( not always) my program stops on line:
while (Globals.PIC.recievingMultiple);
Does anybody knows what is making that fault to happen?
Best regards, Chris
Upvotes: 2
Views: 172
Reputation:
It's failing most likely due to a race condition. I assume that recievingMultiple
is not initialized prior to thread starting so it defaults to false
.
So when you perform the following:
while (Globals.PIC.recievingMultiple);
...there is a chance it is false
and so the while
is skipped entirely.
Using AutoResetEvent
; ManualResetEvent
or at least Interlocked.CompareExchange
; Interlocked.Read
is safer than plain variables.
Spawning a thread just to immediately block on it to complete sort of defeats the purpose of threads.
Upvotes: 3
Reputation: 45119
You should really avoid Thread.Abort()
. If your method given to a thread exits, the thread will automatically be closed. So within your thread simply remove the abort call and leave the method. If you need to pre-exit the thread and like to inform it to do so, than use a CancellationToken
.
Also if you like to create some worker items, that should be handled by a thread in one shot, than provide an immutable list (e.g. an array) of these (also immutable) worker items. The thread itself can then create a list of results that it returns after the work is done. Maybe you should take a look at producer consumer pattern.
Using a shared state that will be manipulated from different threads always leads to hard to debug problems. Immutability is your friend here.
Just for an example the Roslyn compiler internally uses all the way immutable objects and immutable collections just to eliminate most of occurring race conditions.
Upvotes: 4