2013-07-02 22 views
1

我想在後臺線程中動態地創建自定義userControl。 這是我的方法,我在哪裏建立新的線程:調用線程無法訪問此對象錯誤

var thread = new Thread(CreateItemInBackgroundThread); 
thread.SetApartmentState(ApartmentState.STA);    
thread.Start(); 
thread.Join(); 

這是方法CreateItemInBackgroundThread

var uc = new MyUserControl(); 
UserControl item = uc; 
AllControls.Add(item); 
//Here I am trying to add control to a current Tab 
foreach (var currentTab in _allTabs) 
{ 
    currentTab.DocumentWindow.Dispatcher.BeginInvoke(new Action(() => 
                  { 
                   if (tab.DocumentWindow.IsSelected) 
                   { 
                    tempTab = tab; 
                    tempControl = item; 
                    finish = true; 
                   } 

                  })); 
} 

這是我的潤飾性

bool finish 
    { 
     get { return _finish; } 
     set 
     { 
      _finish = value; 
      if (_finish) 
      { 
       tempTab.AnimatedCanvas.Dispatcher.BeginInvoke(new Action(() => tempTab.AnimatedCanvas.Children.Add(tempControl))); 
      } 
     } // Here I get error - The calling thread cannot access this object because a different thread owns it 
    } 

我如何才能避免這個錯誤以及爲什麼會發生此錯誤?

+1

http://stackoverflow.com/questions/11923865/how-to-deal-with-cross-thread-access-exceptions –

+0

此外,爲什麼你會嘗試使用某些特定對象的調度程序?只需使用'Application.Current.Dispatcher'。 –

+0

我想訪問tempControl,在那裏我的動態創建的元素被保存並將其放置到UI,但在我的屬性中,我總是有這個錯誤 – Sasha

回答

0

的錯誤說,你不能因爲不同的線程擁有它,如果調用需要使用tempTab.InvokeRequired

0

此錯誤是因爲來訪問這個對象,所以你可以調用使用Invoke(Delegate Method) 您可以檢查線程你必須在同一個線程上完成不同的任務,比如U不能讓一個線程去異步並且使用同一個線程來更新UI。這會導致衝突。因爲UI線程是主線程。

您可以使用後臺輔助線程和subsribe它的兩個事件處理器到您想要的工作在你的事件。對於EG-

BackgroundWorker Worker=new BackgroundWorker(); 
worker.DoWork+=Yorevent which will do the timeTaking Task(); 
Worker.RunWorkerCompleted+=YOurEvent which will Update your UI after the work is done(); 
worker.RunWorkerAsync(); 

的RunWorkerAsync()會讓你的線程去異步和工作的背景 這樣它不會導致任何線程錯誤太..

+0

好主意,但backgroundWorker在這裏沒有用,因爲我需要創建一個自定義的用戶控件ApartmentState.STA – Sasha

相關問題