简体   繁体   中英

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

您可以通过执行此操作来访问controll

 Invoke(new Action(() => {Foo.Text="Hi";}));

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

You can also access controls via invoke using the following syntax with an Action delegate:

 Invoke((Action)(() =>
 {
      var myVar = SomeWinFormControl.Property;
 }));

您无法从单独的线程访问该控件,它必须来自创建控件的同一线程。

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

I'm assuming that DoWork is launched on another thread. The code accesses ListBox3 , which is a GUI control. .NET restricts access to GUI controls to the thread that created them.

You can do this instead as accessing controls from other than UI thread require invoke.

When you start (I assume you use BackgroundWorker), pass in the url from your textbox to RunWorkerAsync(TxtServer.Text) as argument, then:

private void DoWork(object o, DoWorkEventArgs e)
{
    string Url = (string) e.Argument;

    List<of string> tmpList = new List<of string>;

    var request = createRequest(url, 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.Add(reader.ReadLine());
                    //ResultLabel.Text = "Connected";
                    //use reportprogress() instead
                }
            }
        }
    }
    e.result = tmpList;
}

Then on your Completed event cast e.result to list and add it to your control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM