2011-07-22 55 views
2

我工作的一個項目(C#& WPF),其中一些服務器添加到列表框這樣:的ObservableCollection方法Add()阻塞

ObservableCollection<ServerObjects> servers; 
ServerObjects so = getServers(); 
servers->add(so); 

我的問題是,這個功能被阻斷的同時加入項目到我的列表框中,我只能在生成完成後才能選擇任何東西(程序也會凍結)。

所以,任何想法我該怎麼做才能使這個函數asynk?

謝謝。

+0

「服務器 - >」?你使用不安全的代碼? – Tigran

+0

@ Tigran:你的意思是不安全的代碼是什麼? – Kobe

+0

我的意思是你是如何在C#中獲得「 - >」指針訪問的? – Tigran

回答

1
void addServers(ObservableCollection<ServerObjects> ACollection) 
{ 
    //For Common szenarios dont use new Thread() use instead ThreadPool.QueueUserWorkItem(..) or the TaskFactory 
    Task.Factory.StartNew(()=> this.LoadServer()); 
} 

void MyThreadMethod(Object obj) 
{ 
    ServerObjects so = getServers(); 

    // The invoke is important, because only the UI Thread should update controls or datasources which are bound to a Control 
    UIDispatcher.Invoke(new Action(()=> (obj as ObservableCollection).add(so)); 
} 

你可以做也對RX返回的IObservable訂閱上的TaskScheduler和觀察分派器上。

- >Threadpool vs.s Creating own Thread - >Build More Responsive Apps With The Dispatcher

+0

在使用WPF集合進行多線程時,值得閱讀Bea關於此問題的文章。大多數情況下都可以工作,但有些情況存在問題:http://bea.stollnitz.com/blog/?p=34 – NathanAW

0

像這個?:

void addServers(ObservableCollection<ServerObjects> ACollection) 
{ 
    Thread T = new Thread(new ParameterizedThreadStart(MyThreadMethod)); 
    T.Start(ACollection); 
} 

void MyThreadMethod(Object obj) 
{ 
    ServerObjects so = getServers(); 
    (obj as ObservableCollection).add(so); 
} 

服務器的負載現在另一個線程上執行。

+0

我認爲你需要與UI線程同步。 –

+0

我假設這個集合綁定到一個UI控件。爲此,啓動線程並將非ui線程中的元素添加到集合中並不是一個好主意,因爲這偶爾會以IllegalCrossThreadException結束。 因此,當將元素添加到列表中時,您將不得不在UI線程上重新分派。 你也應該創建這樣的szenarios硬線程。使用ThreadPool或任務並行庫instread –