http://www.idevforfun.com/index.php/2010/01/10/windows-ui-threading/
/// <summary>
/// Something that updates a UI control that
/// might be called from a background thread
/// </summary>
/// <param name="progress"></param>
private void UpdateProgressBar(int progress)
{
//Wrap any code that updates a UI control in this anonymous delegate
Func<int, object> work = delegate(int progressCount)
{
if (progressCount < 0) progressCount = 0;
if (progressCount > 100) progressCount = 100;
progressBar1.Value = progressCount;
if (progressCount == 100) lbl.Text = "Done!";
return null;
};
//Check if we are running on a background thread and if so use Invoke
//otherwise just call the delegate
if (this.InvokeRequired) Invoke(work, progress);
else work(progress);
}
http://www.shawinnes.com/post/Thread-Safe-DotNet-UI-Updates.aspx
public static class ThreadSafeInvokeExtension
{
public static void ThreadSafeInvoke<T>(this T @control, Action<T> toPerform) where T : ISynchronizeInvoke
{
if (@control.InvokeRequired)
@control.Invoke(toPerform, new object[] { @control });
else
toPerform(@control);
}
}
To use the extension method just do something like this:
textBox1.ThreadSafeInvoke(box => box.Text = value);