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在我的服務器上實現線程。
不妨稱之爲'調用()'指定所需的參數,你就已經有你的代表。 'control.Invoke(action,control);' –
好的傑夫。我會說這是下一步...我只是重構... –
'control.Invoke(action,control);'和'control.Invoke(new MethodInvoker(()=> action(控制)));'? –