清理随InvokeRequired乱七八糟的代码 [英] Cleaning up code littered with InvokeRequired

查看:68
本文介绍了清理随InvokeRequired乱七八糟的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,从任何非UI线程操作UI控件时,必须将对UI线程的调用编组,以避免出现问题.普遍的共识是您应该使用测试InvokeRequired,如果为true,则使用.Invoke执行封送处理.

I know that when manipulating UI controls from any non-UI thread, you must marshal your calls to the UI thread to avoid issues. The general consensus is that you should use test InvokeRequired, and if true, use .Invoke to perform the marshaling.

这导致很多代码看起来像这样:

This leads to a lot of code that looks like this:

private void UpdateSummary(string text)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new Action(() => UpdateSummary(text)));
    }
    else
    {
        summary.Text = text;
    }
}

我的问题是这样的:我可以省略InvokeRequired测试,而只是调用Invoke吗?

My question is this: can I leave out the InvokeRequired test and just call Invoke, like so:

private void UpdateSummary(string text)
{
    this.Invoke(new Action(() => summary.Text = text));
}

这样做有问题吗?如果是这样,有没有更好的方法来保留InvokeRequired测试,而不必到处复制和粘贴此模式?

Is there a problem with doing this? If so, is there a better way to keep the InvokeRequired test while not having to copy and paste this pattern all over the place?

推荐答案

那么呢:

public static class ControlHelpers
{
    public static void InvokeIfRequired<T>(this T control, Action<T> action) where T : ISynchronizeInvoke
    {
        if (control.InvokeRequired)
        {
            control.Invoke(new Action(() => action(control)), null);
        }
        else
        {
            action(control);
        }
    }
}

像这样使用它:

private void UpdateSummary(string text)
{
    summary.InvokeIfRequired(s => { s.Text = text });
}

这篇关于清理随InvokeRequired乱七八糟的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆