Writing a server application and my code is starting to get a bit.. repetitive.. Take a look:
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);
}
}
I’m using .NET 4.0. Is there still not a better way to update the GUI from other threads? If it makes any different I am using tasks to implement threading on my server.
You can encapsulate the repetitive logic in another method:
Which you can use like so: