我怎么等到任务在C#中完成?任务、我怎么

由网友(年少小不着调°)分享简介:我想请求发送到服务器并处理返回值:I want to send a request to a server and process the returned value:private static string Send(int id){Task responseTask...

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

I want to send a request to a server and process the returned value:

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;
    }

我使用工作是否正确?我不这么认为,因为发送()方法的返回值的String.Empty 每一次,而打印返回正确的值。

Am I using Task correctly? I don't think so because the Send() method returns string.Empty every time, while Print returns the correct value.

我是什么做错了吗?我如何从一个服务器得到正确的结果?

What am I doing wrong? How do I get the correct result from a server?

推荐答案

您打印方式可能需要等待继续完成(ContinueWith返回,你可以等待一个任务)。否则第二ReadAsStringAsync完成后,该方法返回(前结果在延续分配)。存在于你的发送方法相同的问题。两者都需要等待的延续一贯得到你想要的结果。类似下图

Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below

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;
}
阅读全文

相关推荐

最新文章