Cross-thread operation not valid in Windows Forms

前端 未结 7 1371
醉酒成梦
醉酒成梦 2020-12-11 17:52

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:

相关标签:
7条回答
  • 2020-12-11 18:11

    You can access controll by do this

     Invoke(new Action(() => {Foo.Text="Hi";}));
    
    0 讨论(0)
  • 2020-12-11 18:14

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

    0 讨论(0)
  • 2020-12-11 18:15

    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");
    
    0 讨论(0)
  • 2020-12-11 18:17

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

    0 讨论(0)
  • 2020-12-11 18:18

    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.

    0 讨论(0)
  • 2020-12-11 18:26

    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.

    0 讨论(0)
提交回复
热议问题