简体   繁体   中英

HttpClient PostAsync from controller without result

I'd like to find out what exactly happens in the scenario where i don't need the result of PostAsync call in a scenario when it's called from controller.
For example, i have some action

[HttpPost]
public ActionResult DoSomething(SomeModel model)
{
    ...
    PostDataFireAndForget(model);
    ...
    return new EmptyResult();
}

private void PostDataFireAndForget(SomeModel model)
{
    try
    {
        using (var client = new HttpClient())
        {
            string targetUrl="SomeUrl";
            client.PostAsync(targetUrl, new FormUrlEncodedContent(model.Content));
        }
    }

    catch (Exception ex)
    {
        //we didn't care about the response, no additional requirements here
        //ignore
    }
}

So i'd like to know how exactly it will proceed and why in all possible scenarios. The most interesting one is the scenario where PostAsync takes longer than all the other action code after it so the action completes before PostAsync is finished. Will it get terminated/blocked/finished? Is there any better approach if i want to perform some kind of async stuff in action and don't want to wait for the result?

Make the fire and forget method async all the way so that the exception can be caught and ignored. In its current design it can cause the main action request's thread to fall over.

private async Task PostDataFireAndForgetAsync(SomeModel model) 
    try {
        using (var client = new HttpClient()) {
            var targetUrl="SomeUrl";
            await client.PostAsync(targetUrl, new FormUrlEncodedContent(model.Content));
        }
    } catch (Exception ex) {
        //we didn't care about the response, no additional requirements here
        //ignore
    }
}

By making it async the method can handle (or not handle in this case) the exception and let the other threads continue.

[HttpPost]
public ActionResult DoSomething(SomeModel model) {
    //... fire and forget
    PostDataFireAndForgetAsync(model);
    //...
    return new EmptyResult();
}

A function/method is always called to process an input and present an output, irrelevant if you need the results or not. If you do not want to wait for the result you will have to at least wait for the process to finish, even if you wish to ignore the result.

In your scenario, you are making a request and leaving without any outcome, though all UI process might complete and exit but the application will stay in memory until the async completes. Preferably wait for the async to finish before you completely end all routines.

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