Cross Thread Update UI | .Net

Cross Thread Update UI | .Net

Added by Nasir Mahmood updated on Friday, November 24, 2017

Problem:

Updating UI in multithreading environment is always pain in mind. I have to write code every time to update UI. Fortunately i have found a solution from Best Way to Invoke Any Cross-Threaded Code? so i am sharing this code

Extension Method:

For this problem we make an Extension Method so that we can use it where we want.

public static class Extensions
{
  public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
  {
    if (@this.InvokeRequired)
    {
      @this.Invoke(action, new object[] { @this });
    }
    else
    {
      action(@this);
    }
  }
}				
				

Usage:

Now we can use InvokeEx on any ISynchronizeInvoke and can access the properties and fields of implementing class by following code.

this.InvokeEx(_form => _form._control._function());				
				
this.InvokeEx(delegate {
    MethodName(para1,para2);
    });				
				

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected