Why is Task not awaitable in

2019-04-29 14:49发布

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;
}

2条回答
小情绪 Triste *
2楼-- · 2019-04-29 15:34

Install Async

Tools --> NuGet --> Packet manager console

run below code

Install-Package Microsoft.Bcl.Async -Version 1.0.168 

Ref: https://www.nuget.org/packages/Microsoft.Bcl.Async

查看更多
登录 后发表回答