Consume a Web Service in C#: Remove Task.Wait()

Viewed 141

I am trying to consume a web service. It's an XML based service. I mean response in XML format. The code is working fine. However, I do not want to use task.Wait(). Please let me know how I can replace it with async/await.

Below is my code :

using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ConsoleApp6
{
class Program
{
    static void Main(string[] args)
    {
        Program obj = new Program();
        var result = obj.GetData().Result;
    }

    public async Task<string> GetData()
    {
        string url =
            "https://test.net/info.php?akey=abcd&skey=xyz";
        HttpClient client = new HttpClient();
        HttpResponseMessage response = client.GetAsync(url).Result;
        var responseValue = string.Empty;
        if (response != null)
        {


            Task task = response.Content.ReadAsStreamAsync().ContinueWith(t =>
            {
                var stream = t.Result;
                using (var reader = new StreamReader(stream))
                {
                    responseValue = reader.ReadToEnd();
                }
            });

            task.Wait(); // How I can replace it and use await


        }

        return responseValue;
    }
}

[XmlRoot(ElementName = "Info")]
public class Test
{
    [XmlAttribute(AttributeName = "att")]
    public string SomeAttribute{ get; set; }
    [XmlText]
    public string SomeText{ get; set; }
}

}

2 Answers

You already are in an async context, so just use await:

var stream = await response.Content.ReadAsStreamAsync();

using (var reader = new StreamReader(stream))
{
    responseValue = reader.ReadToEnd();
}
       

That said, you should check all your calls:

HttpResponseMessage response = await client.GetAsync(url);

and make your main async, too and while we are at it make the method static:

public static async Task Main)
{
    var result = await GetData();
}

where your method signature is:

public static async Task<string> GetData()

The static isn't required, but you will find parallel and/or asynchronous programming is a lot easier if you have as little side effects as possible.

You can make Main method async as well and await GetData

static async Task Main(string[] args)
{
    Program obj = new Program();
    var result = await obj.GetData();
}
Related