I would like to use Invoke in getter, how to do it when using .Net 2.0 not e.g. 4.0? For .Net > 2.0 we can use Func and what is replacement for .Net 2.0?
Here is example for .Net 4.0 (from link)
public ApplicationViewModel SelectedApplication
{
get {
if (this.InvokeRequired)
{
return (ApplicationViewModel)this.Invoke(new Func<ApplicationViewModel>(() => this.SelectedApplication));
}
else
{
return _applicationsCombobox.SelectedItem as ApplicationViewModel;
}
}
}
Since you’re using .NET 2.0, you won’t have the
Funcdelegate available to you, but you can use the MethodInvoker delegate.You won’t be able to use the lambda expression syntax with .NET 2.0, but you can use the “anonymous delegate” syntax (which is pretty much the same thing), as shown in the code example below.
Querying data in UI controls from a non-UI thread is generally an uncommon thing to do; usually your UI controls trigger events that execute on the UI thread, so you gather the data you need from your UI controls at that time and then pass that data on to some other function, so you don’t need to worry about doing an Invoke.
In your case, though, you should be able to do something like this:
EDIT: Now that I look at your .NET 4.0 code sample and also look at the Invoke function, I see how it can return a value (not something that I’ve had a reason to use before).
Well, the MethodInvoker delegate does not expect a return value, but as @haiyyu pointed out, you could define your own delegate. For instance, you would just need to define your own
Func<TResult>delegate, and the original code would probably work fine:Sample code from the MSDN page: