wpf wpf中的STA线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12449461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
STA thread in wpf
提问by teardrop
I have a problem with ListViewItem.When i use it in a thread, it display a message:
我在使用 ListViewItem 时遇到问题。当我在线程中使用它时,它会显示一条消息:
"The calling thread must be STA, because many UI components require this."
“调用线程必须是 STA,因为许多 UI 组件都需要它。”
and then I change it to :
然后我将其更改为:
Mythread.SetApartmentState(ApartmentState.STA);
Although when I use it, it display a message again:
虽然当我使用它时,它再次显示一条消息:
"The calling thread cannot access this object because a different thread owns it."
“调用线程无法访问此对象,因为其他线程拥有它。”
I use Dispatcher for it. It display a message again:
我使用 Dispatcher。它再次显示一条消息:
"The calling thread cannot access this object because a different thread owns it."
“调用线程无法访问此对象,因为其他线程拥有它。”
what am I doing to solve problem?
我在做什么来解决问题?
Thread th = new Thread(() =>
{
search.SearchContentGroup3(t, addressSearch.CurrentGroup.idGroup);
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
public void SearchContentGroup3(int id)
{
ListViewItem lst = new ListViewItem();
lst.DataContext = p;
Application.Current.Dispatcher.BeginInvoke(
new Action(() => currentListView.Items.Add(lst)),
DispatcherPriority.Background);
}
回答by Steve Py
If I understand correctly, You want to kick off a worker thread to load an entity of some sort, then create a list view item to represent it.
如果我理解正确,您想启动一个工作线程来加载某种实体,然后创建一个列表视图项来表示它。
My guess would be that the issue is you're creating the list view item in the thread, and attempting to attach it to the list view using the Dispatcher. Instead, try this:
我的猜测是问题在于您正在线程中创建列表视图项,并尝试使用 Dispatcher 将其附加到列表视图。相反,试试这个:
public void SearchContentGroup3(int id)
{
// Do stuff to load item (p?)
// ...
// Signal the UI thread to create and attach the ListViewItem. (UI element)
Application.Current.Dispatcher.BeginInvoke(
new Action(() =>
{
var listItem = new ListViewItem() {DataContext = p};
currentListView.Items.Add(lst);
}),
DispatcherPriority.Background);
}

