Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-thread operation not valid in Windows Forms

Could anyone help me i have a problem I'm trying to get this code to work in the background via threadpool but i cannot seem to get it to work i keep getting this error:

Cross-thread operation not valid: Control 'ListBox3' accessed
from a thread other than the thread it was created on. 

Here is the code i am using:

private void DoWork(object o)
{
    var list = ListBox3;

    var request = createRequest(TxtServer.Text, WebRequestMethods.Ftp.ListDirectory);

    using (var response = (FtpWebResponse)request.GetResponse())
    {
        using (var stream = response.GetResponseStream())
        {
            using (var reader = new StreamReader(stream, true))
            {
                while (!reader.EndOfStream)
                {
                    list.Items.Add(reader.ReadLine());
                    ResultLabel.Text = "Connected";
                }
            }
        }
    }
}
like image 219
Terrii Avatar asked Dec 19 '12 03:12

Terrii


People also ask

What is InvokeRequired in C#?

Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on. public: property bool InvokeRequired { bool get(); }; C# Copy.

What is CheckForIllegalCrossThreadCalls?

CheckForIllegalCrossThreadCalls parameter. The BlueZone ActiveX control is a legacy control that was developed before . NET. It has functionality that will hook into the container window's message processing to intercept messages.


3 Answers

You can access controll by do this

 Invoke(new Action(() => {Foo.Text="Hi";}));
like image 126
Parviz Bazgosha Avatar answered Oct 19 '22 16:10

Parviz Bazgosha


You need to invoke a delegate to update the list. See this MSDN example.

like image 20
jac Avatar answered Oct 19 '22 17:10

jac


This extension method solves the problem too.

/// <summary>
/// Allows thread safe updates of UI components
/// </summary>
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);
    }
}

Use in your worker thread as follows

InvokeEx(x => x.MyControl.Text = "foo");
like image 3
SkeetJon Avatar answered Oct 19 '22 17:10

SkeetJon