Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a method marshalled on the UI Thread need to be thread-safe

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.

like image 544
Dog Ears Avatar asked Jun 24 '11 13:06

Dog Ears


People also ask

How do you handle the UI update from multiple threads?

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.

Are method calls thread safe?

If a method only accesses local variables, it's thread safe.

When should I worry about thread safety?

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.

How do I know if a method is thread safe?

A method will be thread safe if it uses the synchronized keyword in its declaration.


2 Answers

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.

like image 147
CodeNaked Avatar answered Oct 15 '22 15:10

CodeNaked


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++; ));
}
like image 32
Jason Down Avatar answered Oct 15 '22 13:10

Jason Down