Invokes and Delegates in C#
Can someone explain the syntax in this block of code?
Invoke((MethodInvoker)
(
() =>
{
checkedListBox1开发者_C百科.Items.RemoveAt(i);
checkedListBox1.Items.Insert(i, temp);
checkedListBox1.Update();
}
)
);
I'm using a backgroundworker which needs to update parts of the UI so I used this. It works, but I don't know what the empty () and => mean.
() and => is a lambda expression.
Action a = () => {
//code here
}
is a delegate of type Action
, which executes the code in the block.
Func<string> f = () => {
//code here
return "string";
}
is a delegate of type Func<string>
, which executes the code in the block and then returns a string.
Func<int, int, string> f = (i, j) => {
//code here
return "string"+i+j;
}
is a delegate of type Func<int, int, string>
, which has two int parameters referred to i and j in the code block and returns a string.
Etc...
() =>
introduces a lambda expression.
If the lambda expression received parameters then they would be listed inside the parentheses. Your lambda is equivalent to
void foo()
{
...
}
that a Lambda eExpression. The epmty brackets mean that it does not accept any parameters.
Although this snippet seems like it's missing something, don't think it compiles. W
hat Invoke does is call the UI thread. When you do processing, you want to do that on a background thread, and only make short calls to the UI thread. That way you keep the UI responsive.
So this snippts passes a piece of work (add items to the Combobox) to the UI thread to have it done. A background thread cannot directly do things on the UI thread.
Regards GJ
精彩评论