的WinForms线程间修改线程、WinForms

由网友(半情歌)分享简介:每当我想从另一个线程修改的winform,我需要使用Whenever I want to modify a winform from another thread, I need to use- >调用(委托PARAMS) ,以使修改发生在WinForm的自己的线程so that the modificat...

每当我想从另一个线程修改的winform,我需要使用

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

- >调用(委托PARAMS)

,以使修改发生在WinForm的自己的线程

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

对于每个需要修改GUI功能,我需要另一位代表的功能。

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.

我觉得我的问题可以适用于所有的语言在这里的winform可以运行

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

推荐答案

如果您正在使用C#3,您可以使用的lambda,而在C#2,使用匿名委托。这些简化的语法时,有没有必要重复使用的行为。有一件事我一直做的是做同步的形式code,而不是在控制器中。该控制器不应该打扰这些类型的管道的问题,更具体的技术,而不是控制器逻辑。

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();
    }
}

作为一种实践,使你的形式调用所有公共方法InvokeOnFormThread。或者,你可以使用AOP来拦截public方法在表单上呼吁,并呼吁InvokeOnFormThread,但上面已经已经足够好了(如果你是一致的,记得要经常做的形式或用户控件上的公共方法)。

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

阅读全文

相关推荐

最新文章