Cross-thread operation not valid in Windows Forms

旧街凉风 提交于 2019-11-28 13:48:28
jac

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

You can access controll by do this

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

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

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

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

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.

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