我想在後臺線程中動態地創建自定義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
}
我如何才能避免這個錯誤以及爲什麼會發生此錯誤?
http://stackoverflow.com/questions/11923865/how-to-deal-with-cross-thread-access-exceptions –
此外,爲什麼你會嘗試使用某些特定對象的調度程序?只需使用'Application.Current.Dispatcher'。 –
我想訪問tempControl,在那裏我的動態創建的元素被保存並將其放置到UI,但在我的屬性中,我總是有這個錯誤 – Sasha