我怎么等到任务在C#中完成? [英] How do I wait until Task is finished in C#?

查看:142
本文介绍了我怎么等到任务在C#中完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于我怎么等到任务在C#中完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆