c# - 如何等到任务在 C# 中完成?

标签 c# .net task task-parallel-library wait

我想向服务器发送请求并处理返回值:

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/

相关文章:

c# - 表单操作中的 MVC ASP.NET Url.Action,将表单数据传递给它

c# - 从 SQL 数据库中读取架构名称、表名称和列名称并返回到 C# 代码

c# - FileInfo 的空对象模式

.net - 如何用回调包装 3rdParty 函数以便能够等待回调完成然后从回调函数返回结果?

cocoa - 如何在 Objective-C/Cocoa 中执行 shell 命令 "ping"并将结果转换为字符串?

c# - 如何使用 CIDR 表示法查看 IP 地址是否属于 IP 范围内?

.net - 在 F# 中组合异步计算

c# - C# 中的 WMI 查询在非英语机器上不起作用

c# - 寻找导致未观察到 "A Task' 异常的原因...”

c# - 如何限制物体旋转到一定程度?