How do I want untill is finished in C#?

Posted by Grienders on Stack Overflow See other posts from Stack Overflow or by Grienders
Published on 2012-11-03T16:56:30Z Indexed on 2012/11/03 17:00 UTC
Read the original article Hit count: 190

Filed under:
|

Let's say, I want to send a request to a server and get a result from it:

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

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

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET