【问题标题】:Cross thread invoke exception跨线程调用异常
【发布时间】:2017-06-17 12:49:22
【问题描述】:

为了通过另一个线程更改控件,我需要调用委托来更改控件但是,它正在抛出TargetParameterCountException

private void MethodParamIsObjectArray(object[] o) {}
private void MethodParamIsIntArray(int[] o) {}

private void button1_Click(object sender, EventArgs e)
{
        // This will throw a System.Reflection.TargetParameterCountException exception
        Invoke(new Action<object[]>(MethodParamIsObjectArray), new object[] { });
        // It works
        Invoke(new Action<int[]>(MethodParamIsIntArray), new int[] { });
}

为什么用MethodParamIsObjectArray 调用会抛出异常?

【问题讨论】:

  • 不知道为什么在button1_Click 中需要Invoke 考虑到当前线程已经是UI 线程

标签: c# winforms


【解决方案1】:

这是因为Invoke 方法的签名为:

object Invoke(Delegate method, params object[] args)

args参数前面的params关键字表示该方法可以接受不定数量的对象作为参数。当您提供对象数组时,它在功能上等同于传递多个以逗号分隔的对象。以下两行在功能上是等效的:

Invoke(new Action<object[]>(MethodParamIsObjectArray), new object[] { 3, "test" });
Invoke(new Action<object[]>(MethodParamIsObjectArray), 3, "test");

将对象数组传递到Invoke 的正确方法是将数组转换为类型Object

Invoke(new Action<object[]>(MethodParamIsObjectArray), (object)new object[] { 3, "test" });

【讨论】:

    【解决方案2】:

    Invoke 需要一个包含参数值的对象数组。

    在第一次调用中,您没有提供任何值。您需要一个值,令人困惑的是,它本身就是一个对象数组。

    new object[] { new object[] { }  }
    

    在第二种情况下,您需要一个包含整数数组的对象数组。

    new object[] { new int[] { }  }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      相关资源
      最近更新 更多