Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Task<HttpResponseMessage> not awaitable in my project?

I have a project that is targeting the .NET 4 framework and I've created a method which updates data in a database. The method itself also uses a flag (runAsync) to determine whether it should run asynchronously or not. I'm getting an error that 'System.Threading.Tasks.Task< HttpResponseMessage > is not awaitable' but I am using this same code in another application and it works fine. What am I doing wrong, or what am I missing to get this to work?

Here is the code:

public static async Task<object> UpdateData(SecureData data, string userAgent, bool runAsync)
{
    object result;

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

            HttpResponseMessage response = runAsync
                                                ? await client.PutAsJsonAsync(String.Format("api/securedata/update/{0}", data.Token), data)
                                                : client.PutAsJsonAsync(String.Format("api/securedata/update/{0}", data.Token), data).Result;

            result = runAsync
                            ? await response.Content.ReadAsAsync<object>()
                            : response.Content.ReadAsAsync<object>().Result;

            response.EnsureSuccessStatusCode();
        }
    }
    catch (HttpRequestException ex)
    {
        throw new HttpRequestException(ex.Message, ex.InnerException);
    }

    return result;
}
like image 210
freakinthesun Avatar asked Jul 30 '14 17:07

freakinthesun


People also ask

What is Task ActionResult?

Task<ActionResult> represents ongoing work with a result of ActionResult. The await keyword was applied to the web service call. The asynchronous web service API was called ( GetGizmosAsync ).

Does Task run Use thread pool?

The main purpose of Task. Run() is to execute CPU-bound code in an asynchronous way. It does this by pulling a thread from the thread pool to run the method and returning a Task to represent the completion of the method.

Does Task run block thread?

Run is misused to run IO blocking tasks. Although the code will work just fine (e.g UI not not freeze) but it is still a wrong approach. This is because Task. Run will still block a thread from thread pool the entire time until it finishes the method.

What is synchronous and asynchronous in MVC?

A traditional ASP.NET MVC control action will be synchronous by nature; this means a thread in the ASP.NET Thread Pool is blocked until the action completes. Calling an asynchronous controller action will not block a thread in the thread pool.


1 Answers

You cannot use async/await on ASP.NET 4.0. You must upgrade to 4.5.

like image 125
Stephen Cleary Avatar answered Oct 21 '22 13:10

Stephen Cleary