.

Cross-thread operation not valid

Trying to update a control from another thread will throw an error similar to below:
Cross-thread operation not valid: Control ‘BusyForm’ accessed from a thread other than the thread it was created on.
The solution to this is to wrap your code in a thread-safe wrapper (see method ThreadSafe_Close) as follow:

public partial class BusyForm : Form
{
    public BusyForm()
    {
        InitializeComponent();
    }

    public void ThreadSafe_Close()
    {
        if (InvokeRequired)
        {
            Invoke(new Action(ThreadSafe_Close));
            return;
        }

        Close();
    }
}

void Main()
{
    BusyForm b = new BusyForm();
    b.Show();
    Action<string> AsyncMethod = (input) => 
            { Thread.Sleep(2000); };
    AsyncMethod.BeginInvoke("Input", (asyncResult) =>
        {
            //OLD CODE: b.Close(); throws an error!! 
            b.ThreadSafe_Close();
        }, AsyncMethod);
}

What's your thoughts on this?

*

Protected by WP Anti Spam