在wpf中的STA线程

时间:2012-09-16 18:22:28

标签: wpf multithreading dispatcher sta

我有一个ListViewItem的问题。当我在一个线程中使用它时,它会显示一条消息:

  

“调用线程必须是STA,因为许多UI组件都需要这个。”

然后我将其更改为:

Mythread.SetApartmentState(ApartmentState.STA);

虽然当我使用它时,它会再次显示一条消息:

  

“调用线程无法访问此对象,因为另一个线程拥有它。”

我使用Dispatcher。它再次显示一条消息:

  

“调用线程无法访问此对象,因为另一个线程拥有它。”

我在做什么来解决问题?

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);
}

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你想启动一个工作线程来加载某种实体,然后创建一个列表视图项来代表它。

我的猜测是问题是您在线程中创建列表视图项,并尝试使用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);
}