views:

532

answers:

2

First of all, I'm using VS2005 and C# 2.0.

I'm trying to set a combobox' Text property from inside the SelectedIndexChanged event. From another thread here on StackOverflow this was proposed done the following way:

BeginInvoke(new Action(() => someCombobox.Text = "x" ));

Now, first of all this returns a compiler error for me. I believe that is because the Action object behaves differently in the two language specifications. In C# 2.0, the Action object seems to need the <T> structure in all declarations. Maybe I'm wrong, but I'd like to have that clarified.

What does work is the following:

BeginInvoke(new Action<string>( delegate { someCombobox.Text = "x"; }), new object[] { "" });

However, it just seems very weird to me that I have to define the Action object with a type parameter (especially since I'm not intending to pass any parameters)! Somehow removing this parameter would also make the empty new object[] obsolete, which is what I want.

Can anyone help me simplify the above call?

Finally, is it guaranteed that BeginInvoke will finish after the SelectedIndexChanged and thus update the combobox' Text property with the correct text?

I'd really appreciate to learn the answers to these questions.

+7  A: 

I don't think Action without parameters is available in .NET 2.0 No worries - just use a different predefined delegate type. MethodInvoker should do the job (void method with no parameters).

Also, BeginInvoke has 2 overloads - one that takes a delegate, and one that takes a delegate and array of objects.

BeginInvoke(new MethodInvoker(delegate()
{
    someCombobox.Text = "x";
}));
Filip
I've used `MethodInvoker` many times before `System.Action` came around. :)
280Z28
+5  A: 

You could define your own Action delegate.

delegate void Action()

I can't see the object on which you're calling BeginInvoke, but if it is a UI control created on the same thread as the combobox, the delegate you pass is guaranteed to be invoked some time after the SelectedIndexChanged event handler completes.

Senthil Kumar