【发布时间】:2013-07-02 10:14:56
【问题描述】:
我正在尝试在后台线程中创建动态自定义 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
}
我怎样才能避免这个错误以及为什么会发生这个错误?
【问题讨论】:
-
另外你为什么要尝试使用某些特定对象的调度程序?只需使用
Application.Current.Dispatcher。 -
我想访问 tempControl,我的动态创建的元素被保存并放到 UI 中,但是在我的属性中我总是出现这个错误
标签: c# wpf multithreading