VansFannel
VansFannel

Reputation: 45941

How can avoid set my method as async when I'm using ReadAsStringAsync()?

I'm developing a library with C# and .NET Framework 4.0.

I have this method to PUT something on a ASP.NET Web Api 2 web service.

public async Task<string> PrepareAndStartv2(
    string orderNumber,
    string userName,
    string systemName)
{
    string uri =
        string.Format(PrepareAndStartUri, orderNumber, userName, systemName);

    string batchName = null;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(webApiHost);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpContent content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

        Task<HttpResponseMessage> response = client.PutAsync(uri, content);
        HttpResponseMessage message = response.Result;

        Task<string> task = message.Content.ReadAsStringAsync();

        batchName = await task;
    }

    return batchName;
}

I added message.Content.ReadAsStringAsync() to get a string returned by the method. And after that I've been forced to and Task<string>, await and async everywhere.

Is there another option to read a string in a HttpContent without using await, Task<string> and async?

Maybe running a Task inside this PrepareAndStartv2 method that wait will I'm reading the string with ReadAsStringAsync().

Upvotes: 1

Views: 75

Answers (1)

Sami
Sami

Reputation: 146

You can use Task.Result after calling an async method to avoid your own method to be forced async:

public string PrepareAndStartv2(
    string orderNumber,
    string userName,
    string systemName)
{
    string uri =
        string.Format(PrepareAndStartUri, orderNumber, userName, systemName);

    string batchName = null;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(webApiHost);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpContent content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

        HttpResponseMessage message = client.PutAsync(uri, content).Result;
        batchName = message.Content.ReadAsStringAsync().Result;
    }

    return batchName;
}

Upvotes: 3

Related Questions