在异步任务更新UI期间更改文本框文本

时间:2017-06-10 01:01:05

标签: c# winforms asynchronous task .net-4.6.2

这是我的简单代码:

CFoo

在运行这些代码期间,我无法移动TextBox1&的滚动条。我可以在foo行之后看到日志 如何在CFoo工作期间取消阻止TextBox1?

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

private async void button1_Click(object sender, EventArgs e)
{
    string reader_str = "";

    textBox1.Text = "Test 1" + Environment.NewLine;          
    await Task.Run(() =>
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(main_url + "Appointment/LoadVisaAppointmentTypeDetail?id=");
        req.Method = "GET";
        req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8";
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
        req.ContentType = "text/html; charset=utf-8";
        req.KeepAlive = true;
        req.Timeout = 25000;
        req.AllowAutoRedirect = true;
        res = (HttpWebResponse)req.GetResponse();
        Stream Stream = res.GetResponseStream();
        StreamReader reader = new StreamReader(Stream);
        reader_str = reader.ReadToEnd();
    });
    textBox1.AppendText(reader_str + Environment.NewLine + Environment.NewLine);

    textBox1.AppendText("Test 2" + Environment.NewLine);
    await Task.Run(() =>
    {
        // ...
    });
    textBox1.AppendText(reader_str + Environment.NewLine + Environment.NewLine);
}