C # Invoke () delegate with array of strings as argument (winforms)

I am trying to use this.Invoke () from a separate thread to access the controls in my form. I am invoking a delegate that points to a method with the string [] as an argument.

A few lines regarding my delegate declaration:

public delegate void delVoidStringArray(string[] s); public delVoidStringArray _dLoadUserSelect = null; _dLoadUserSelect = LoadUsers; 

Calling a delegate from a separate thread:

 Invoke(_dLoadUserSelect, sUsernames); 

And the method called to work with controls in the form

 private void LoadUsers(string[] users) { //Load the list of users into a ListBox lstUsers.Items.AddRange(users); //Load the state of a CheckBox on the form chkUserAlways.Checked = Properties.Settings.Default.PreferDefaultUser; } 

This usually works with the rest of my delegates with different arguments (string, control, form and lack of arguments), but whenever I call this line of Invoke (), I get the error message "Parameter counter mismatch."

I think what happens is that my string array is placed in an array of objects, and the delegate is trying to pass these strings as separate arguments to the method. Therefore, if there were "Bob", "Sally" and "Joe" in the string array, he tries to call LoadUsers as

 LoadUsers("Bob", "Sally", "Joe"); 

which obviously does not match the signature.

Does this sound like something could happen? How can I get around this problem?

+4
source share
1 answer

Assuming sUsernames is string[] , then yes, you should call it

 Invoke(_dLoadUserSelect, new object[] { sUsernames }); 

.Net arrays are covariant, so this assignment is valid:

 string[] sUsernames = new[] { "a", "b", "c" }; object[] objs = sUsernames; 

and when calling a method with params parameters, the array is passed directly, and not passed as the first element of the argument array. You need to manually create an array of arguments for Invoke to get the expected behavior.

+4
source

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


All Articles