If I Invoke a method onto the UI Thread is it searilized by the Windows message queue and subsequently doesn't need to be re-entrant?
private void CalledFromWorkerThread()
{
//changed from 'InvokeRequired' Anti-Pattern
this.Invoke((Action) (() => _counter++; /* Is this ok? */ ));
}
Clarification: It is only the UI thread that will be accessing _counter.
1) Have each thread set a "DataUpdated" flag when new data is available, and have the UI periodically check for new data. 2) Create each thread with a callback to a UI Update(...) method to be called when new data becomes available.
If a method only accesses local variables, it's thread safe.
Save this answer. Show activity on this post. Thread safety becomes a concern if there is at least a single entry point which can be accessed by multiple threads. If a piece of code is accessed by multiple threads and is calling other method/class/etc., then all this code tree becomes vulnerable.
A method will be thread safe if it uses the synchronized keyword in its declaration.
What you have is fine, assuming _counter
is only accessed by the UI thread.
If two threads call your CalledFromWorkerThread
, then _counter will be properly incremented and thread-safe with what you have.
Based on the clarification, that only the UI thread is accessing _counter, you don't need a lock. I've updated my example. I prefer coding it this way to avoid the extra if invoke required check.
private void CalledFromWorkerThred()
{
this.Invoke((Action) (() => _counter++; ));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With