使用BeginInvoke时出现参数计数不匹配异常

Parameter count mismatch exception when using BeginInvoke

本文关键字:不匹配 异常 参数 BeginInvoke 使用      更新时间:2023-10-16

我在一个运行async的C++.NET表单应用程序中有一个后台工作者。在这个后台工作者的DoWork函数中,我想将行添加到数据网格视图中,但我真的不知道如何使用BeginInvoke来实现这一点,因为我的代码似乎不起作用。

我有的代码

delegate void invokeDelegate(array<String^>^row);
....
In the DoWork of the backgroundworker
....
array<String^>^row = gcnew array<String^>{"Test", "Test", "Test"};
if(ovlgrid->InvokeRequired)
    ovlgrid->BeginInvoke(gcnew invokeDelegate( this, &Form1::AddRow), row);
....
void AddRow(array<String^>^row)
{
 ovlgrid->Rows->Add( row );
}

我得到的错误是:

类型为的未处理异常中出现"System.Reflection.TargetParameterCountException"mscorlib.dll

附加信息:参数计数不匹配。

当我更改为不传递任何参数的代码时,它只是起作用,代码变为:

delegate void invokeDelegate();
...
In the DoWork function
...
if(ovlgrid->InvokeRequired)
     ovlgrid->BeginInvoke(gcnew invokeDelegate( this, &Form1::AddRow));
...
void AddRow()
{
     array<String^>^row = gcnew array<String^>{"test","test2","test3"};
     ovlgrid->Rows->Add( row );
}

但是问题是我想要传递参数。我想知道我做错了什么,导致了parametercountexception,以及如何解决这个问题?

您遇到的问题是BeginInvoke获取参数的数组,然后您将恰好是一个参数的数组传递给它。

参数

方法

类型:System.Delegate

方法的委托,该方法接受args中指定的参数,该参数被推送到Dispatcher事件队列中。

args

型号:System.Object[]

要作为参数传递给给定方法的对象数组。可以是null

因此,BeginInvoke将其视为方法具有3字符串参数:"test""test2""test3"。您需要传递一个仅包含row:的数组

array<Object^>^ parms = gcnew array<Object^> { row };
ovlgrid.BeginInvoke(gcnew invokeDelegate(this, &Form1::AddRow), parms);