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

后端 未结 5 1042
北海茫月
北海茫月 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 11:58

    This may be obvious to most, but you can take the accepted answer and add another method if you need to retrieve the value...

    public static T SynchronizedFunc(this ISynchronizeInvoke sync, Func func)
    {
        if (!sync.InvokeRequired)
        {
            // Execute the function
            return func();
        }
    
        // Marshal onto the context
        return (T) sync.Invoke(func, new object[] { });
    }
    

    I used this recently to get handle of the form in a thread-safe way...

    var handle = f.SynchronizedFunc(() => f.Handle);
    

提交回复
热议问题