Cross-thread operation not valid in Windows Forms

前端 未结 7 1441
醉酒成梦
醉酒成梦 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: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 tmpList = new List;
    
        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.

提交回复
热议问题