C# - Thread-safe GUI updates

By , 8/15/2012
(1 ratings)
If you want to communicate from a background thread with the User Interface of a Windows Form Application, you have to do this using invoke. The snippet below shows how to write a method that decides itself wether an invoke is needed or not.

Author: Thorsten Hans, translation by Michael List
Translate to VB
/// <summary>
/// This method is called by a background thread (not UI thread).
/// </summary>
/// <param name="max">Maxiumum amount of iterations</param>
private void BackgroundThreadAction(int max)
{
    if (max < 0)
    {
        InvokeIfRequired(this.textBoxStatus, (MethodInvoker)delegate()
        {
            this.textBoxStatus.Text = "max value must be greater than zero";
        });
        return;
    }
    for (int i = 0; i < max; i++)
    {
        InvokeIfRequired(this.textBoxStatus, (MethodInvoker)delegate()
        {
            this.textBoxStatus.Text = String.Format("Processing value {0}", i);
        });
        Thread.Sleep(10);
    }
}

/// <summary>
/// Method that performs UI interactions.
/// </summary>
/// <param name="target">Control to be updated. If multiple controls have to be updated, the parent control has to be passed.</param>
/// <param name="methodToInvoke">The delegate that is wanted to be executed (UI actions)</param>
private void InvokeIfRequired(Control target, Delegate methodToInvoke)
{
    /* InvokeRequired checks wether the call can go directly to the UI or
        * if Invoking is needed.
        */
    if (target.InvokeRequired)
    {
        // Control has to be updated via invoke because the update is called by a background thread
        target.Invoke(methodToInvoke);
    }
    else
    {
        // UI-Update can be called directly
        methodToInvoke.DynamicInvoke();
    }
}

Comments

 

Log in, to comment!