1

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

  • Use `async/await` instead of `Dispatcher.Invoke` Refactor your code so you *don't* mix up background processing and UI updates. If you want to report progress use `Progress` – Panagiotis Kanavos Oct 10 '18 at 07:09

2 Answers2

2

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 });
}
bommelding
  • 2,969
  • 9
  • 14
0

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.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443