Thursday, 12 March 2015

Thread-Safe Calls to Windows Forms Controls [.NET Framework 4.5]

Thread-Safe Calls to Windows Forms Controls

.NET Framework 4.5


As access to the controls in Windows Form applications is not inherently thread safe. If any one have multiple threads manipulating the state of a control, possibly it force the control into an inconsistent state. Other thread related bugs such as rece conditions or deadloacks are also possible.



But you can perform your required task safely using some tricks.



Use the following extensions and just pass the action like:




dataGridView1.PerformSafely(() => dataGridView1.SelectAll());

OR


dataGridView1.PerformSafely(() => dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText);


OR


panel1.PerformSafely(() => panel1.Visible = false);

Extension class:


public static class CrossThreadExtensions
{
    public static void PerformSafely(this Control target, Action action)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action);
        }
        else
        {
            action();
        }
    }

    public static void PerformSafely<T1>(this Control target, Action<T1> action,T1 parameter)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, parameter);
        }
        else
        {
            action(parameter);
        }
    }

    public static void PerformSafely<T1,T2>(this Control target, Action<T1,T2> action, T1 p1,T2 p2)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, p1,p2);
        }
        else
        {
            action(p1,p2);
        }
    }
}

3 comments:

  1. Wow very nice informative post...The coding is really much more helpful for beginners...Thanks for updating these types of informative updates..
    PHP Training in Chennai

    ReplyDelete
  2. Nice info regarding Thread-Safe Calls to Windows Forms Controls my sincere thanks for sharing this post please Continue to share this post
    Dot Net Training in Chennai

    ReplyDelete
  3. nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blogs.
    dotnet training in chennai

    ReplyDelete