我想向服务器发送请求并处理返回值:
private static string Send(int id)
{
Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
string result = string.Empty;
responseTask.ContinueWith(x => result = Print(x));
responseTask.Wait(); // it doesn't wait for the completion of the response task
return result;
}
private static string Print(Task<HttpResponseMessage> httpTask)
{
Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
string result = string.Empty;
task.ContinueWith(t =>
{
Console.WriteLine("Result: " + t.Result);
result = t.Result;
});
task.Wait(); // it does wait
return result;
}
我是否正确使用了 Task
?我不这么认为,因为 Send()
方法每次都返回 string.Empty
,而 Print
返回正确的值。
我做错了什么?如何从服务器获得正确的结果?
最佳答案
您的 Print 方法可能需要等待继续完成(ContinueWith 返回一个您可以等待的任务)。否则第二个 ReadAsStringAsync 完成,该方法返回(在继续分配结果之前)。您的发送方法中存在同样的问题。两者都需要等待继续才能始终如一地获得您想要的结果。类似下面
private static string Send(int id)
{
Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
string result = string.Empty;
Task continuation = responseTask.ContinueWith(x => result = Print(x));
continuation.Wait();
return result;
}
private static string Print(Task<HttpResponseMessage> httpTask)
{
Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
string result = string.Empty;
Task continuation = task.ContinueWith(t =>
{
Console.WriteLine("Result: " + t.Result);
result = t.Result;
});
continuation.Wait();
return result;
}
关于c# - 如何等到任务在 C# 中完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13211334/