DEV Community

Cover image for Cross thread calls made easier
Adam K Dean
Adam K Dean

Posted on

2

Cross thread calls made easier

Back in 2010 I wrote a blog post about cross thread calls, showing how to overcome invalid cross-thread operations and change windows forms from other threads. It was simple but a little bit messy.

Well, things are easier now, and have been for a while. Instead of declaring delegates and invoking them, you can now use generic delegates and save yourself the hassle of declaring new delegates for every method signature.

For example, where before you had to do this:

private delegate void ObjectDelegate(object obj);

private void UpdateTextBox(object obj)
{
    if (InvokeRequired)
    {
        ObjectDelegate method = new ObjectDelegate(UpdateTextBox);
        Invoke(method, obj);
        return;
    }
}
Enter fullscreen mode Exit fullscreen mode

You can now do this:

private void UpdateTextBox(string s)
{
    if (InvokeRequired)
    {
        Action<string> action = new Action<string>(UpdateTextBox);
        Invoke(action, s);
        return;
    }
}
Enter fullscreen mode Exit fullscreen mode

Another great thing is if you have to pass multiple objects then it's as simple as adding more types within the angle brackets. You can also substitute Action<T> for var to save space. Let's say for example, you need to update a label from another thread, the follow works great:

private void UpdateLabel(Label label, string s)
{
    if (InvokeRequired)
    {
        var action = new Action<Label, string>(UpdateLabel);
        Invoke(action, label, s);
        return;
    }

    label.Text = s;
}
Enter fullscreen mode Exit fullscreen mode

This will save you a bunch of time, and is essentially identical to the previous method.

For more information on Action<T> Delegates, see this MSDN article.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay