Parameter counter mismatch exception when using BeginInvoke

I have a backgroundwork worker in a C ++ .NET forms application that runs async. In the DoWork function of this background worker, I want to add rows to a datagridview, however I cannot figure out how to do this with BeginInvoke, since the code I have does not seem to work.

The code that I have

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 ); } 

The error I am getting is:

An unhandled exception of type "System.Reflection.TargetParameterCountException" occurred in mscorlib.dll

Additional information: mismatch of the parameter counter.

When I switch to the code, so as not to pass any parameters, it just works, the code becomes the following:

 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 ); } 

The problem is that I want to pass parameters. I was wondering what I am doing wrong, what causes the occurrence of parametercount and how to fix it?

+4
source share
1 answer

The problem you are facing is that BeginInvoke takes an array of parameters , and you pass it an array, which, as it turned out, is a parameter.

Parameters

Method

Type: System.Delegate

The delegate to the method that accepts the parameters specified in args , which is placed in the dispatcher event queue.

arg

Type: System.Object[]

An array of objects passed as arguments to this method. May be null .

Therefore, BeginInvoke implies that you have 3 string parameters: "test" , "test2" and "test3" . You need to pass an array containing only your row :

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

Source: https://habr.com/ru/post/1393787/


All Articles