Диспетчер C # WPF - не могу понять это правильно - PullRequest
0 голосов
/ 03 марта 2011

Я пытаюсь внести изменения в пользовательский интерфейс, а затем запустить функцию вот мой код:

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..";
}

функция, которую я хочу запустить после обновления пользовательского интерфейса / после окончания «запуска» ThreadStart:

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

Так что я должен делать? Заранее спасибо, Дин.

Ответы [ 2 ]

2 голосов
/ 03 марта 2011

Полагаю, вы хотите выполнить какое-то действие асинхронно. Правильно? Для этого я рекомендую использовать в WPF класс BackgroundWorker :

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

Надеюсь, это ваш вопрос.

1 голос
/ 03 марта 2011

Немного запутался в том, что вы пытаетесь достичь, но я верю, что это то, что вам нужно ...

    private void btnAddChange_Document(object sender, RoutedEventArgs e)
    {
        System.Threading.ThreadStart start = delegate()
        {
            //do intensive work; on background thread
            string x = "";
            for (int i = 0; i <= 1000; i++)
            {
                x += i.ToString();
            }

            //done doing work, send result to the UI thread
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, 
                new Action<int>(changest));

        };

        //perform UI work before we start the new thread
        this.BusyIndicator_CompSelect.IsBusy = true;
        this.MainWindow_parent.BusyIndicator_MainWindow.IsBusy = true;
        t = "Creating document 1/2..";

        //create new thread, start it
        new System.Threading.Thread(start).Start();
    }

    public void changest(int x)
    {
        //show the result on the UI thread
        MessageBox.Show(x.ToString());
    }
...