"thread-safe updates of a winform control from other classes" Code Answer

5

delegate can be used for thread safe calls

check this http://msdn.microsoft.com/en-us/library/ms171728.aspx

            // this delegate enables asynchronous calls for setting
    // the text property on a textbox control.
    delegate void settextcallback(string text);

    // this method demonstrates a pattern for making thread-safe
    // calls on a windows forms control. 
    //
    // if the calling thread is different from the thread that
    // created the textbox control, this method creates a
    // settextcallback and calls itself asynchronously using the
    // invoke method.
    //
    // if the calling thread is the same as the thread that created
    // the textbox control, the text property is set directly. 

    private void settext(string text)
    {
        // invokerequired required compares the thread id of the
        // calling thread to the thread id of the creating thread.
        // if these threads are different, it returns true.
        if (this.textbox1.invokerequired)
        {   
            settextcallback d = new settextcallback(settext);
            this.invoke(d, new object[] { text });
        }
        else
        {
            this.textbox1.text = text;
        }
    }
By Julian Jocque on September 28 2022

Answers related to “thread-safe updates of a winform control from other classes”

Only authorized users can answer the Search term. Please sign in first, or register a free account.