Search code examples
c#wpfdispatcher

C# WPF dispatcher - can't get it right


I am trying to make a change in the UI and then make my function run here's my code:

private void btnAddChange_Document(object sender, RoutedEventArgs e)
{
   System.Threading.ThreadStart start = delegate()
   {
      // ...

      // This will throw an exception 
      // (it's on the wrong thread)
      Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(changest));

      //this.BusyIndicator_CompSelect.IsBusy = true;
      
      //this.MainWindow_parent.BusyIndicator_MainWindow.IsBusy = true;
   };
   // Create the thread and kick it started!
   new System.Threading.Thread(start).Start();
}

public void changest()
{
    this.BusyIndicator_CompSelect.IsBusy = true;
    this.MainWindow_parent.BusyIndicator_MainWindow.IsBusy = true;
    t = "Creating document 1/2..";
}

the function I want to run after the ui updates / after the ThreadStart 'start' has ended:

string x = "";
for(int i =0;i<=1000;i++)
{
   x+= i.ToString();
}
MessageBox.Show(x);

So what am I supposed to do?


Solution

  • I assume you want to execute some action asynchronous. Right? For this, I recommend using in WPF the BackgroundWorker-class:

    BackgroundWorker bgWorker = new BackgroundWorker() { WorkerReportsProgress=true};  
    bgWorker.DoWork += (s, e) => {      
        // Do here your work
        // Use bgWorker.ReportProgress(); to report the current progress  
    };  
    bgWorker.ProgressChanged+=(s,e)=>{      
        // Here you will be informed about progress and here it is save to change/show progress. 
        // You can access from here savely a ProgressBars or another control.  
    };  
    bgWorker.RunWorkerCompleted += (s, e) => {      
       // Here you will be informed if the job is done. 
       // Use this event to unlock your gui 
    };  
    // Lock here your GUI
    bgWorker.RunWorkerAsync();  
    

    I hope, this is what your question is about.