Control.Invoke带输入参数 [英] Control.Invoke with input Parameters

查看:241
本文介绍了Control.Invoke带输入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我在C#中发现的Control.Invoke方法要求您使用委托没有输入参数。有没有解决这个办法吗?我想调用一个方法来更新从另一个线程的用户界面,并传递给字符串参数吧。

From what I've found in C#, the Control.Invoke method requires that you use a delegate with no input parameters. Is there any way around this? I would like to invoke a method to update the UI from another thread and pass to string parameters to it.

推荐答案

的哪个版本C#中您使用的?如果您正在使用C#3.5,你可以使用闭包,以避免传递的参数。

Which version of C# are you using? If you are using C#3.5 you can use closures to avoid passing in parameters.

public static class ControlExtensions
{
  public static TResult InvokeEx<TControl, TResult>(this TControl control,
                                             Func<TControl, TResult> func)
    where TControl : Control
  {
    return control.InvokeRequired
            ? (TResult)control.Invoke(func, control)
            : func(control);
  }

  public static void InvokeEx<TControl>(this TControl control,
                                        Action<TControl> func)
    where TControl : Control
  {
    control.InvokeEx(c => { func(c); return c; });
  }

  public static void InvokeEx<TControl>(this TControl control, Action action)
    where TControl : Control
  {
    control.InvokeEx(c => action());
  }
}



安全调用的代码现在变得微不足道。

Safely invoking code now becomes trivial.

this.InvokeEx(f => f.label1.Text = "Hello World");
this.InvokeEx(f => this.label1.Text = GetLabelText("HELLO_WORLD", var1));
this.InvokeEx(() => this.label1.Text = DateTime.Now.ToString());





public class MyForm : Form
{
  private delegate void UpdateControlTextCallback(Control control, string text);
  public void UpdateControlText(Control control, string text)
  {
    if (control.InvokeRequired)
    {
      control.Invoke(new UpdateControlTextCallback(UpdateControlText), control, text);
    }
    else
    {
      control.Text = text;
    }
  }
}

使用简单,但你,必须定义更多的回调,更多的参数

Using it simple, but you have to define more callbacks for more parameters.

this.UpdateControlText(label1, "Hello world");

这篇关于Control.Invoke带输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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