Loading ...

Invokeifrequired Template

Hello everybody,

today I want to document simple but very useful feature if you work with multiple threads in Winforms application. 

Quite often it happens that you execute in some paralel thread long running calculations and would like time from the time notify results to UI. 

But if you try to do this then you'll get an error that will say to you that parallel thread doesn't have permissions to some control because it didn't create such a control. So, how then update UI?

The answer is simple, you should use method Invoke of the control. In that case everything inside of method Invoke will be executed from UI thread. 

Needless to say that such approach is workable but to some degree cumbersome. So in order to simplify life I've created following extension method:

public static class Extensions
{
    public static void InvokeIfRequired(this ISynchronizeInvoke obj, MethodInvoker action)
    {
        if (obj.InvokeRequired)
        {
            var args = new object[0];
            obj.Invoke(action, args);
        }
        else
        {
            action();
        }
    }
}

And then in order to update text box field following logic was enough:

txtLog.InvokeIfRequired(() =>
{
    txtLog.Text += "\r\n check following id SubAccount: " + foundItem.RowId;
});