Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

c# - WinForms interthread modification

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

->Invoke(delegate, params)

so that the modification occurs in the winform's own thread.

For every function that needs to modify the gui, I need another delegate function.

Is there some scheme which allows me to limit the number of delegate functions needed? I have a controller class which handles the whole gui in one spot, I've thought about reusing delegates but that smells badly.

I think that my question can apply to all languages where winform can run

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...