简体   繁体   中英

Getting error at await in Async Task concept

Folks, I am getting error at await response.Content.ReadAsAsync<ManifestStatusEntity>();

as Cannot await something

I have seen the tutorials and implemented the code but not sure about the errors.

public async Task  dataRowSpy_RowChanged(object sender, DataRowChangedEventArgs e)
{
    //TODO: Process the new request
    using (var client = new HttpClient())
    {
        try
        {
            client.BaseAddress = new Uri("http://localhost:9667/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
            HttpResponseMessage response = await client.GetAsync("api/psms/getmanifeststatus").Result;
            if (response.IsSuccessStatusCode)
            {
                ManifestStatusEntity manifestStatusEntity =  await response.Content.ReadAsAsync<ManifestStatusEntity>();
                newManifestVersion = Convert.ToInt32(manifestStatusEntity.Version);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}

This web API gets an Int value. Is anything else that I need to implement?

The actual problem in your code is further up, here:

HttpResponseMessage response = await client.GetAsync("api/psms/getmanifeststatus").Result;

The Await keyword will asynchronously return the result of a task. The .Result property will synchronously return the result of a task. The problem, is that you're calling .Result , which returns a HttpResponseMessage synchronously, and then calling await on the HttpResponseMessage object instead of the task.

HttpResponseMessage response = await client.GetAsync("api/psms/getmanifeststatus");

Try this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM