2011-09-18 53 views
2

寫一個服務器應用程序,我的代碼開始變得有點..重複..請看:如何減少從其他線程更新GUI控件時的重複?

private void AppendLog(string message) 
{ 
    if (txtLog.InvokeRequired) 
    { 
     txtLog.Invoke(new MethodInvoker(() => txtLog.AppendText(message + Environment.NewLine))); 
    } 
    else 
    { 
     txtLog.AppendText(message); 
    } 
} 

private void AddToClientsListBox(string clientIdentifier) 
{ 
    if (listUsers.InvokeRequired) 
    { 
     listUsers.Invoke(new MethodInvoker(() => listUsers.Items.Add(clientIdentifier))); 
    } 
    else 
    { 
     listUsers.Items.Add(clientIdentifier); 
    } 
} 

private void RemoveFromClientsListBox(string clientIdentifier) 
{ 
    if (listUsers.InvokeRequired) 
    { 
     listUsers.Invoke(new MethodInvoker(() => listUsers.Items.Remove(clientIdentifier))); 
    } 
    else 
    { 
     listUsers.Items.Remove(clientIdentifier); 
    } 
} 

我使用.NET 4.0。是否還沒有更好的方法從其他線程更新GUI?如果它使任何不同我使用tasks在我的服務器上實現線程。

回答

3

您可以封裝在另一種方法重複的邏輯:

public static void Invoke<T>(this T control, Action<T> action) 
    where T : Control { 
    if (control.InvokeRequired) { 
    control.Invoke(action, control); 
    } 
    else { 
    action(control); 
    } 
} 

,您可以使用像這樣:

listUsers.Invoke(c => c.Items.Remove(clientIdentifier)); 
+1

不妨稱之爲'調用()'指定所需的參數,你就已經有你的代表。 'control.Invoke(action,control);' –

+0

好的傑夫。我會說這是下一步...我只是重構... –

+0

'control.Invoke(action,control);'和'control.Invoke(new MethodInvoker(()=> action(控制)));'? –