Thursday, 12 March 2015

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

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

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);
        }
    }
}