Shortest way to write a thread-safe access method to a windows forms control

后端 未结 5 1045
北海茫月
北海茫月 2020-12-02 11:47

In this article:

http://msdn.microsoft.com/en-us/library/ms171728(VS.80).aspx

The author uses the following method to make thread-safe calls to a Windows For

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 12:17

    Edit: I should mention I would not consider this to be a Best Practice

    If you are using 3.5 you can make an extension method to the effect of:

    public static void SafeInvoke(this Control control, Action handler) {
        if (control.InvokeRequired) {
            control.Invoke(handler);
        }
        else {
            handler();
        }
    }
    

    this is basically taken from: Here

    Then use it like:

    textBox1.SafeInvoke(() => .... );
    

    Of course modify the extension etc for your usages.

提交回复
热议问题