2015-05-22 71 views
1

我有一個很長的操作,我想顯示擴展工具箱繁忙指示器。我做了一個關於此的前一篇文章,它是固定的Wpf Extended toolkit BusyIndicator not showing during operation。然而,在這個調用過程中,我不得不與UI元素(畫布)交互,我得到一個「調用線程必須是STA,因爲許多UI組件需要這個」。我瞭解(現在)後臺工作人員(見代碼):在STA線程上顯示繁忙指示器

 private void CboItemId_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 

     BackgroundWorker _backgroundWorker = new BackgroundWorker(); 
     _backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork); 
     _backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted); 
     ItemSearchBusyIndicator.IsBusy = true; 

     // Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; 
     if (RdoItemSearch.IsChecked == false) return; 
     ///backgroundWorker_DoWork(null, null); 

     if (CboItemId.SelectedValue == null) return; 
     if (CboItemId.SelectedValue.ToString() != string.Empty) 
     { 
      selectedItem = CboItemId.SelectedValue.ToString(); 
      _backgroundWorker.RunWorkerAsync(); 
     } 
     // Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow; 
    } 

    public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) 
    { 

      LoadItemData(selectedItem); 
    } 

使用MTA並且不能設置爲STA。所以我試圖調用使用UI elelment在自己的線程內部功能:

 public void LoadItemData(string itemId) 
    { 

     Axapta ax = new Axapta(); 
     files.Clear(); 
     try 
     { 
      ax.Logon(Settings.Default.Server, null, Settings.Default.Test, null); 
      AxaptaContainer path = (AxaptaContainer)ax.CallStaticClassMethod(Settings.Default.ClassName, Settings.Default.ItemData, itemId); 
      for (int i = 1; i <= path.Count; i++) 
      { 
       AxaptaContainer somestring = (AxaptaContainer)path.get_Item(i); 
       for (int j = 1; j <= somestring.Count; j += 2) 
       { 
        string extension = Path.GetExtension(somestring.get_Item(j + 1).ToString().ToLower()); 
        if (extension == ".jpg" 
         || extension == ".jpeg" 
         || extension == ".gif" 
         || extension == ".png" 
         || extension == ".bmp" 
         || extension == ".pdf") 
         /* key=path - value=description */ 
         files.Add(somestring.get_Item(j + 1).ToString(), somestring.get_Item(j).ToString()); 
       } 
      } 

      // _canvas.Children.Clear(); 
      Thread t = new Thread(new ThreadStart(LoadPictures)); 
      t.SetApartmentState(ApartmentState.STA); 
      t.Start(); 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     finally 
     { 
      ax.Logoff(); 
     } 
    } 

繼承人在那裏我與畫布元素進行交互:

 private void LoadPictures() 
    { 

     foreach (DictionaryEntry filePath in files) 
     { 

      try 
      { 

       Picture p = new Picture(); 
       ToolTip t = new ToolTip(); 
       t.Content = filePath.Value; 
       p.ToolTip = t; 
       TextBlock tb = new TextBlock(); 
       tb.Text = filePath.Value.ToString(); 
       Canvas.SetTop(tb, y); 
       Canvas.SetLeft(tb, x); 

        p.ImagePath = filePath.Key.ToString(); 
        p.OriginalImagePath = filePath.Key.ToString(); 
        p.ImageName = filePath.Value.ToString(); 
        _canvas.Children.Add(p); //<-------This is where i seem to error 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error:" + ex.Message,"File Load Error",MessageBoxButton.OK,MessageBoxImage.Error); 
      } 
     } 
    } 

但我得到一個「調用線程不能訪問這個對象,因爲不同的線程擁有它「 我不知道如何調用長時間運行(LoadItemData())函數,同時顯示BusyIndi​​cator沒有backgroundworker。任何幫助表示讚賞

+0

你爲什麼不讓它更簡單,你用control.Dispatcher對象? –

+0

請參閱http://stackoverflow.com/questions/7428260/wp7-invalid-cross-thread-access-scheduledtaskagent/7428442#7428442,它應該與wpf類似 – thumbmunkeys

+1

您必須從BGW的RunWorkerCompleted事件處理函數中調用LoadPictures() 。 –

回答

1

有多種方法:

1)Async binding,但不建議,但它的存在。您可以在屬性getter中運行長時間運行的任務,框架將阻止UI被阻塞,當它完成時 - UI將會更新。

2)使用BackgroundWorkerTask/Thread運行代碼,但將其調用到UI線程中。在你的例子中:

Dispatcher.InvokeAsync(() => _canvas.Children.Add(p)); 

3)你可以完全阻止主窗口的UI線程,沒有問題。但要說明有關其正在忙碌,您可以在另一個線程創建窗口,並顯示有忙碌狀態(運行動畫等):

 var thread = new Thread(() => 
     { 
      var window = new SomeWindow(); 
      window.ShowDialog(); 
     }); 
     thread.SetApartmentState(ApartmentState.STA); 
     thread.IsBackground = true; 
     thread.Start(); 
+0

使用Dispatcher.Invoke((=)_canvas.Children.Add(p));我得到一個錯誤:「不能轉換lambda表達式鍵入'System.Delegate',因爲它不是委託類型」 – rigamonk

+0

我將第二個建議轉換爲:Dispatcher.Invoke((Action)(()=> _canvas.Children.Add (p)));因爲它不會編譯。但我仍然得到「調用線程無法訪問此對象,因爲不同的線程擁有它」的錯誤。是否因爲我正在用新線程調用LoadPicture()? – rigamonk

+0

我不確定,這可能意味着我的回答是錯誤的。你能發佈完整的異常消息嗎? – Sinatr