MoonLight MoonLight -4 years ago 95
C# Question

Change textbox Text during async Task-Update UI

Here is my simple codes :

private async void button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "";
await MyMethodAsync();
}

public async Task MyMethodAsync()
{
TextBox1.Text = "Test 1" + Environment.NewLine;

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);
string reader_str = reader.ReadToEnd();
...
TextBox1.Text += "Test 2" + Environment.NewLine;
...
TextBox1.Text += "Done";
}


During running these codes i can not move scroll bar of TextBox1 & i can see the log after the
Done
line.

How can i unblock TextBox1 during
async Task MyMethodAsync()
working?

Answer Source

You could try something like this:

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);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download