2011-09-18 55 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(控制)));'? –