开发者

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.


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++; ));
}


It will delegate the call from the same thread, does not necessarily mean everything else you do in that function will be thread-safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜