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()
.