简体   繁体   中英

Handle return value of background Task - Async Await

I have a long running method that I wish to run on a background thread. The method uses the MailChimp api to subscribe a long list of email addresses.

I don't want my "Web Forms" app to hang whilst this task runs but I do want to handle any exceptions that occur.

We call the following method to get things running:

ExecuteAsyncBatchRegistration(mcitems);

Below is the method we just called:

public async Task ExecuteAsyncBatchRegistration(List<MailChimpItem> mcitems)
{
    GenericResponse response = new GenericResponse();

    await Task.Run(() =>
    {
        response = ExecuteBatchRegistration(mcitems);

        if (response.Success == false)
        {
            ErrorHandler.WriteError(response.Exception);
        }
    });
}

The method call ErrorHandler.WriteError() uses HttpContext.Current so that it can tell me the page URL, IP address etc. However, in this instance HttpContext.Current is NULL.

I can resolve this by changing the method as follows:

public async Task ExecuteAsyncBatchRegistration(List<MailChimpItem> mcitems)
{
    GenericResponse response = new GenericResponse();

    response = await Task<GenericResponse>.Run(() =>
    {
        return ExecuteBatchRegistration(mcitems);
    });

    if (response.Success == false)
    {
        ErrorHandler.WriteError(response.Exception);
    }
}

The problem with the latter version of the method is that the app hangs: it doesn't appear to run asynchronously in the background.

How can I run this method asynchronously and retain HttpContent.Current?

If you do not want your web form to hang (ie. you want to return the result to the user and offload the process) then you need to capture the data you need from the HttpContext and pass that to your offloaded long running Task. Do not access the HttpContext again in that Task because there will not be one. If you want the HttpContext to be available then you cannot end the request which means the form will "hang" and you do your processing on the Request thread. The only other good alternative to keep the HttpContext without making the user's web browser hang is to make the call using javascript. Normally I suggest not running it at all in the web context but offload it to a service or use something like HangFire but both of these have the same limitation that you cannot communicate with any type of HttpContext , you have to gather the state and pass it to the off loaded Task.

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