1

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().

VansFannel
  • 45,055
  • 107
  • 359
  • 626
  • 2
    Possible duplicate of [How would I run an async Task method synchronously?](http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously) – CSharpie Jan 29 '16 at 07:41
  • Of course, it is a duplicate question. I will add my solution as an answer to share knowledge. – VansFannel Jan 29 '16 at 08:06

1 Answers1

3

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;
}
Sami
  • 136
  • 4
  • Stephen Cleary: _"[.Result can easily cause **deadlock** in async code.](http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously)"_ –  Jan 29 '16 at 07:50