Dailycode.info

Short solution for short problems

Setting the property of a control from a seperate thread using an extension method.

In this post you can find a solution that implements an extension method to change the properties of a Windows Forms Control. It’s a large improvement for my previous post: http://www.dailycode.info/Blog/post/2011/04/18/Multi-Threading-and-accessing-controls-from-seperate-threads-in-WPF.aspx

Now this extension will provide the functionality on any control of your form. This is the function that does the magic:

/// <summary>  

/// Executes the Action asynchronously on the UI thread, does not block execution on the calling thread.  

/// </summary>  

/// <param name="control"></param>  

/// <param name="code"></param>  

public static void UIThread(this Control @this, Action code)

{

    if (@this.InvokeRequired)

    {

        @this.BeginInvoke(code);

    }

    else

    {

        code.Invoke();

    }

}

 

Can it be more simpler? This can save a lot of developer time and is one of my latest high impact findings thanks to: http://stackoverflow.com/questions/661561/how-to-update-gui-from-another-thread-in-c

 

Here are some examples on  how to implement this:

Setting some text in a textbox from a separate thread:

this.UIThread(() => lblSubAction.Text = @"Reading Records...");

 

Changing the value of a progressbar:

 

this.UIThread(() => pgbSub.Value = pgbSub.Value + pgbSub.Step);

 

Setting a property of a third party control:

this.UIThread(() => numRecordsFound.EditValue = countForLambda);