Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are possible issues if we await a long async operation in ASP.NET Core?

Consider these two controller methods:

public async Task DoAsync() {
    await TaskThatRunsFor10MinutesAsync().ConfigureAwait(false);
}

public void DoWithTaskRunAndReturnEarly() {
    Task.Run(() => TaskThatRunsFor10MinutesAsync());
}

Let's say on the client side we don't care about the response. We might wait for it to complete, we might abandon it half-way due user refreshing the page -- but it doesn't matter that DoWithTaskRunAndReturnEarly returns earlier.

Is there an important server-side difference between those two approaches, e.g. in reliability, timeouts, etc? Does ASP.NET Core ever abort threads on a timeout?

like image 276
Andrey Shchekin Avatar asked Apr 26 '17 23:04

Andrey Shchekin


People also ask

What happens when async method is not awaited?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Which is the recommended way to wait for an async method to complete?

No problem, just make a loop and call this function with an await: [code] for (int i = pendingList. Count - 1; i >= 0; i--)

Does async await improve performance?

The main benefits of asynchronous programming using async / await include the following: Increase the performance and responsiveness of your application, particularly when you have long-running operations that do not require to block the execution.


1 Answers

In ASP.NET Core 1.1 the socket will stay in the CLOSE_WAIT state until the application Task completes. That could lead to resource exhaustion on the server side if you have lots of long running tasks on the server where the client has already disconnected (refreshed the page in your case).

Is there an important server-side difference between those two approaches, e.g. in reliability, timeouts, etc? Does ASP.NET Core ever abort threads on a timeout?

Thread aborts aren't a "thing" in .NET Core anymore and wouldn't work for async code anyways (there's no active thread when you're awaiting).

In the next version of ASP.NET Core (2.x at time of writing) the RequestAborted cancellation token trigger when the client socket sends a FIN so you'll be able to react to clients disconnecting to cancel long running work. On top of that, it will close the socket even before the application completes.

like image 117
davidfowl Avatar answered Oct 03 '22 09:10

davidfowl