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;
}
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 ).
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.
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.
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.
You cannot use async
/await
on ASP.NET 4.0. You must upgrade to 4.5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With