在winform程序(C#)中,async Task没有返回正确的结果,我的代码如下:
public async void method1()
{
await Task.Run(() =>
{
System.Threading.Thread.Sleep(2000);
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new Action(() => textBox1.Text += "AAAAAAAAAAAA\r\n"));
}
});
if(textBox1.InvokeRequired)
{
textBox1.Invoke(new Action(() => textBox1.Text += "BBBBBBBBBB\r\n"));
}
}
public async Task<string> method2()
{
string result = string.Empty;
System.Net.WebClient wc = new System.Net.WebClient();
Stream st = await wc.OpenReadTaskAsync("https://msdn.microsoft.com/en-us/library/hh191443(v=vs.110).aspx#What Happens in an Async Method");
//Task<Stream> st= wc.OpenReadTaskAsync("https://msdn.microsoft.com/en-us/library/hh191443(v=vs.110).aspx#What Happens in an Async Method");
//Stream st2 = st.Result;
StreamReader sr = new StreamReader(st);
result = sr.ReadToEnd();
return result;
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text += method2()+"\r\n";
method1();
textBox1.Text += "CCCCCCCCCCCC\r\n";
}
System.Threading.Tasks.Task`1 [System.String]
CCCCCCCCCCCC
AAAAAAAAAAAA
1)method2,我想返回页面内容,但事实上,它是&#34; System.Threading.Tasks.Task`1 [System.String]&#34;
2)string&#34; BBBBBBBBBB&#34;没有在textBox1中添加,这是为什么?
答案 0 :(得分:-1)
像这样更改按钮点击事件
private async void Button_Click..
替换
textBox1.Text += method2()+"\r\n";
要
textBox1.Text += await method2()+"\r\n";