【发布时间】:2017-12-15 11:04:45
【问题描述】:
在winform程序(C#)中,异步任务没有返回正确的结果,我的代码如下:
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
啊啊啊啊啊啊
我的问题:
1)方法2,我想返回页面内容,其实是"System.Threading.Tasks.Task`1[System.String]"
2)textBox1中没有添加字符串“BBBBBBBBBB”,这是为什么?
【问题讨论】:
-
你的方法是异步的,所以你需要
await结果。您在此处的代码行:method2()+"\r\n";在Task<string>上调用ToString()。您需要等待两个方法调用才能获得您期望的结果。 -
请问,“await”应该放在哪里?谢谢。我尝试这样的代码: Task
st= wc.OpenReadTaskAsync("msdn.microsoft.com/en-us/library/hh191443(v=vs.110).aspx#What Happens in an Async Method");流 st2 = 等待 st.Result;然后,抛出一个异常:can not waiting -
button1_Click中的代码应该类似于:var method2result = await method2(); textBox1.Text += method2result+"\r\n";. You'll also need to mark the method as async.method1` 根本不需要异步,实际上是不正确的。请参阅this question 了解正确的实现方式。