【问题标题】:Update control from another thread in C# 2.0从 C# 2.0 中的另一个线程更新控件
【发布时间】:2011-06-19 03:47:24
【问题描述】:

我在 .NET 3.0 中使用此代码

Action xx = () => button1.Text = "hello world";
this.Invoke(xx);

但是当我在 .NET 2.0 中尝试它时,我认为 Action 具有这样的类型参数:

Action<T>

如何在.NET 2.0中实现第一个代码?

【问题讨论】:

    标签: c# .net winforms multithreading parallel-processing


    【解决方案1】:

    试试这个:

    this.Invoke((MethodInvoker) delegate
    {
        button1.Text = "hello world";
    });
    

    虽然Action 是在 .NET 2.0 中引入的,但您不能在 .NET 2.0 中使用 lambda 表达式 () =&gt; ... 语法。

    顺便说一句,你仍然可以在 .NET 2.0 中使用Action,只要你不使用 lambda 语法:

    Action action = delegate { button1.Text = "hello world"; };
    Invoke(action);
    

    【讨论】:

    • 这个工作..但是aligray的答案,为什么我得到那个错误..无法将匿名方法转换为类型'System.Delegate',因为它不是委托类型..我想想,还是一样..
    【解决方案2】:

    Action&lt;T&gt;是签名,只是表示action代表的方法必须带一个参数。参数的类型是什么,取决于Invoke调用的签名。

    如何表示Action的各种签名的一些代码示例:

    var noArgs = () => button1.Text = "hello world"; // Action
    var oneArg = (arg) => button1.Text = "hello world"; // Action<T>
    var twoArgs = (arg1, arg2) => button1.Text = "hello world"; // Action<T,T>
    

    如果您不需要使用方法的参数,那很好。但是你仍然需要在 lambda 表达式中声明它们。

    现在,这并不能回答如何从 .NET 2.0 执行此操作,但我假设(可能是不正确的,如果我错了,请纠正我)您不知道 lambdas 如何对应于 Action 类型。

    【讨论】:

      猜你喜欢
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      相关资源
      最近更新 更多