簡體   English   中英

C#WPF調度程序-無法正確處理

[英]C# WPF dispatcher - can't get it right

我試圖在UI中進行更改,然后使我的函數運行,這是我的代碼:

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

ui更新后/ ThreadStart'start'結束后我要運行的功能:

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

那我該怎么辦? 謝謝你,丁。

我假設您要異步執行一些操作。 對? 為此,我建議在WPF中使用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();  

希望這就是您的問題。

對您要完成的目標有點困惑,但是我相信這就是您追求的目標...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM