1

How to fix this error:

Error: Keyword 'this' is not valid in a static property, static method, or static field initializer

Here is the faulty code:

private void proxietype_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Dispatcher.BeginInvoke(((Action)delegate
    {
        Thread t = new Thread(new ThreadStart(() => Check()));
        t.Start();
    }));
}

public static void Check()
{
    ((UserControlVPN)Window.GetWindow(this)).notification.IsActive = true;
    main.notification.IsActive = true;
    main.notification.Message.Content = "Please wait";
}

Here as a Picture :

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
Lyze
  • 13
  • 4
  • 1
    why do you need `Check()` to be static? – Corentin Pane May 25 '20 at 16:04
  • Does this answer your question? ["Keyword 'this' is not valid in a static property, static method, or static field initializer" when adding methods to an ExpandoObject](https://stackoverflow.com/questions/4537141/keyword-this-is-not-valid-in-a-static-property-static-method-or-static-fiel) – Corentin Pane May 25 '20 at 16:18

1 Answers1

0

1) You don't need a Dispatcher to run the Thread or Task asynchonously

2) Use Task instead of Thread

3) You may access to instance via static field assigned e.g. in constructor

4) Also you may get an exception while accessing Window properties from other than Main UI Thread. Here you'll need a Dispatcher.

private void proxietype_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Task.Run(() => Check());
}

// define static field
private static UserControlVPN _thisWindow;

public UserControlVPN()
{
    // assign instance to the field in constructor
    _thisWindow = (UserControlVPN)Window.GetWindow(this);
}

public static void Check()
{
    Dispatcher.BeginInvoke((Action)() =>
    {
        _thisWindow.notification.IsActive = true;
        _thisWindow.notification.Message.Content = "Please wait";
    });
    //...
}

Or you may just remove static. Bacause with this implementation you may have only one instance of the UserControl with no problems.

5) Better to use async/await approach and modify the Window's properties outside of Task.

private async void proxietype_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    proxietype.Enabled = false;
    main.notification.IsActive = true;
    main.notification.Message.Content = "Please wait";
    await Task.Run(() => Check());
    main.notification.Message.Content = "";
    main.notification.IsActive = false;
    proxietype.Enabled = true;
}

public static void Check()
{
    // do job...
}

Be sure that you have no unhandled exceptions possible inside of Check().

aepot
  • 4,558
  • 2
  • 12
  • 24