2013-04-26 79 views
0

我學習C#和剛啓動的線程概念到實踐。我無法更新列表框來顯示實際來自除主線程以外的其他線程的數據。更新不更新列表框

private void DoThreadBtn_Click(object sender, EventArgs e) 
{ 
    ListBoxS.DataSource = sl.dump(); //This update the ListBox. 
    //t = new Thread(dumpList); //This don't update the Listbox 
    //t.Start(); 
} 
TestForm.ListBoxTest.StringList sl = new ListBoxTest.StringList(); 
public void dumpList() 
{ 
    ListBoxS.DataSource = sl.dump(); //Returns a List<string>() 
} 

這是哪裏錯?爲了解決這個問題,我應該學習哪一部分?主題或代表或Lamda?

回答

1

在WinForms應用程序CAL:

public void dumpList() 
{ 
    if (this.InvokeRequired) 
    { 
     this.Invoke(new MethodInvoker(this.dumpList)); 
     return; 
    } 

    ListBoxS.DataSource = sl.dump(); //Returns a List<string>() 
} 

如果控件的句柄是在不同的線程比當前的調用線程,性能InvokeRequired =真(othervise假)

+0

它的工作;!你能解釋一下嗎?我看到它會進入第一個條件並遞歸調用相同的函數。 – Jones 2013-04-26 12:06:50

+0

欲瞭解更多信息 - MSDN: http://msdn.microsoft.com/cs-cz/library/ms171728.aspx – misak 2013-04-26 12:10:22

+0

感謝。我會通過它。 – Jones 2013-04-26 12:13:04

0

在VB中我喜歡這樣做這種方式(概念應結轉到C#幾乎相同)

這裏是我想從另一個線程更新我的UI。想象一下,「子方法」更新UI,並從另一個線程調用DoMethod。請注意,在我的情況下,我正在使用數據模板更新綁定到可觀察集合的列表框。在我的代碼中,我必須調用listbox.items.refresh來讓屏幕反映我的更改。我真的很新的WPF和VB(脾氣暴躁的老C++的Win32/MFC的傢伙),所以這可能是最可怕的代碼永遠。

注 - 省略號(...)是可變的參數列表。我喜歡將它匹配到我的原始子參數列表。

Delegate Sub DelegateMethod(...) 
Sub Method(...) 

End Sub 

Public Sub DoMethod(...) 

    Dim DM As DelegateMethod = AddressOf Method 
    Me.Dispatcher.Invoke(DM, ...) 

End Sub