Cross-thread operation not valid in Windows Forms

…衆ロ難τιáo~ 提交于 2019-12-29 01:39:50

问题


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

回答1:


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




回答2:


You can access controll by do this

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



回答3:


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

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



回答4:


You can't access the control from a separate thread, it has to be from the same thread that the control was created from.




回答5:


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



回答6:


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.




回答7:


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.



来源:https://stackoverflow.com/questions/13945225/cross-thread-operation-not-valid-in-windows-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!