简体   繁体   中英

Call async method HttpClient without await throw error

When i call async method using httpclient without await cause i don't want to wait response then throw exception "object reference not set to an instance of an object"

\\ Call PostAsync
var ignore = webRequest.PostAsync(json, token);

\\ PostAsync method
using (var httpClient = new HttpClient())
{
    if (!string.IsNullOrEmpty(auth))
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", auth);

    var content = new StringContent(json, Encoding.UTF8, "application/json");   
    // this line throw exception
    var response = await httpClient.PostAsync(this.URL, content);
    if (response.IsSuccessStatusCode)
    {
        result = await response.Content.ReadAsStringAsync();
    }                    
}

and then i get error on my visual studio image below.

image

if i don't want to wait response, how i do it?

I think the problem is the basic concept of async await, check this link for a clearer idea:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

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