0

My code is something like this:

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    //...
    //Code some data changes
    //...
    Task.Factory.StartNew(() => { this.Dispatcher.Invoke(() => ChangeSettings()) });
}

private void ChangeSettings()
{
    this.Dispatcher.Invoke(() =>
    {
       window.IsEnabled = false;
       //to see enabled/disabled changes
       Thread.Sleep(1000);
       someLabel.Content = "Something";
       window.IsEnabled = true;
    }); 
}

If I keep Task.Factory.StartNew in btnSave_Click event, I see the window change from disable to enable. But if I change Task to another Dispatcher.Invoke, the window don't get disable. Could someone explain me why? And the difference between Dispatcher.Invoke and Task. Thank you so much

EDIT: Scenario is: I want to update in background a second window from first window after somethings change.

Yatimex
  • 1
  • 1
  • Use Task.Run instead of StartNew, see e.g. here: https://stackoverflow.com/a/38423486/1136211. Besides that, Dispatcher.Invoke is something completely different. It is not meant to start an asynchronous task or do anything at all "in the background". – Clemens Feb 16 '22 at 11:26

1 Answers1

0

Using Task.Factory.StartNew(...) will run the lambda function provided on a thread pool thread (aka a background thread). This is commonly used for tasks that will consume a lot of processing power and therefore would slow down the GUI thread, which is responsible for rendering the GUI and handling input. This would be a seen as the GUI "freezing" while it processes this CPU instensive work.

The Dispatcher of the GUI control is the dispatcher for the GUI thread. This is used to "marshal" or run stuff on the GUI thread itself from other threads. So if you have code executing on a background thread and want to post some lambda function to be executed on the GUI thread you use the Dispatcher.Invoke.

This is important because usually at the end of the processing of these CPU intensive tasks, we want ot provide some update to the GUI. GUI updates can only be made from the GUI thread. Therefore we need to Invoke them on the dispatcher for the GUI control.

ekke
  • 1,280
  • 7
  • 13
  • Thanks. So if I change the task to Dispatcher.Invoke in the event, isn't there any possibilities that I see first the window disable and the enable? – Yatimex Feb 16 '22 at 11:21