Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Avoiding InvokeRequired

0.00/5 (No votes)
27 Apr 2012 1  
This is an alternative for C# Pivot Table

Introduction

This minor article is an enhancement to the excellent piece of work by Pablo Grisafi.  The goal is to enhance Pablo's code to work in cases where controls are not all created on the same (usually "UI") thread. 

Using the code  

The enhancement is relatively minor and virtually everyone with enough understanding of delegates and generics could easily enhance Pablo's version as I did below.  While Pablo's version works for 95+% cases, in very special circumstances, a control might need to be created on another thread, thus requiring InvokeRequired check on that control's property -- not on the form's.  The idea behind these enhancements is to allow the extension method to handle this type of scenario.  

The code below helps ensure that all controls are updated on the thread on which they were created even when they were created on different threads.  

static class ControlExtensions
{
  public static void InvokeOnOwnerThread<T>(this T control, Action<T> invoker) where T : Control
  {
    if (control.InvokeRequired)
      control.Invoke(invoker, control);
    else
      invoker(control);
  }
}  

The code that uses this extension method would look like this: 

private void UpdateFormTextFromSomeThread(string message)
{
  this.InvokeOnOwnerThread((form) => form.Text = message);  
}

History

No changes. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here