John Smith
John Smith

Reputation: 8871

How to reduce repetition when updating GUI controls from other threads?

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.

Upvotes: 2

Views: 168

Answers (1)

Jordão
Jordão

Reputation: 56537

You can encapsulate the repetitive logic in another method:

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

Which you can use like so:

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

Upvotes: 3

Related Questions