WinForms interthread modification

前端 未结 4 1819
傲寒
傲寒 2020-12-21 13:46

Whenever I want to modify a winform from another thread, I need to use

->Invoke(delegate, params)

so that the modification occurs in the winf

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-21 14:04

    If you're using C# 3, you can use lambda, and in C# 2, use anonymous delegates. These simplify the syntax when there's no need to reuse the behavior. One thing I always do is to do the synchronization in the form code, not in the controller. The controller shouldn't be bothered with these sort of "plumbing" problems that are more specific to the technology than to the controller logic.

    public void ResetFields()
    {
        // use "delegate" instead of "() =>" if .Net version < 3.5
        InvokeOnFormThread(() => 
        {
            firstInput.Text = Defaults.FirstInput;
            secondInput.Text = Defaults.SecondInput;
            thirdChoice.SelectedIndex = Defaults.ThirdChoice;
        });
    }
    
    // change Action to MethodInvoker for .Net versions less than 3.5
    private void InvokeOnFormThread(Action behavior) 
    {
        if (IsHandleCreated && InvokeRequired)
        {
            Invoke(behavior);
        }
        else
        {
            behavior();
        }
    }
    

    As a practice, make all public methods in your form call "InvokeOnFormThread." Alternately, you could use AOP to intercept public method calls on your form and call "InvokeOnFormThread," but the above has worked well enough (if you're consistent and remember to always do it on public methods on the form or UserControls).

提交回复
热议问题