Reputation: 1937
I have something I must do in the UI thread. Therefore I do that :
Dispatcher.Invoke(() =>{ what I must do in the UI thread}
When I put this line inside a function, it works but it doesn't work inside a delegate like in this example:
public Action f = () => // it does'nt work
{
Dispatcher.Invoke(() => {what I must do in the UI thread });
}
public void ff() // it works
{
Dispatcher.Invoke(() => { what I must do in the UI thread });
}
The error is the following :
a field initializer can not reference the non-static-field, method or property DispatcherObjet.Dispatcher
Upvotes: 1
Views: 140
Reputation: 3037
You cannot reference this.Dispatcher
in an initializer.
The following should work or at least move the error to what I must do in the UI thread
public Action f = () => // it should work
{
Application.Current.Dispatcher.Invoke(() => {what I must do in the UI thread });
}
Upvotes: 2
Reputation: 174279
You need to initialize the field f
in the constructor:
public class YourClassName
{
public Action f;
public YourClassName()
{
f = () =>
{
Dispatcher.Invoke(() => {what I must do in the UI thread });
}
}
}
What's going on is that f
is a field of your class. Field initializers like the one you used have no access to instance members of the class but only to static members.
If you need to have access to instance members, you need to initialize the field in an instance member like the constructor.
Upvotes: 0