Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications for incomplete async tasks in .NET 4.5?

Tags:

c#

async-await

Suppose you have a web handler that calls an asynchronous method like such:

var foo = await SomeMethod();

And, due to poor coding (no CancellationToken, no timeouts, etc), SomeMethod never completes. The frustrated user, in turn, presses "stop" on her browser and goes to the pub.

Suppose this happens to a lot of users.

I know that I can write a timeout to prevent it from waiting eternally, but if I do not... what happens? Is this a memory leak? Does it get cleaned up eventually? What's the worst-case scenario?

like image 455
roufamatic Avatar asked Jan 11 '14 06:01

roufamatic


2 Answers

And SomeMethod never returns. The user cancels the request and goes to the pub.

Those are not the same thing, at all.

If SomeMethod never completes, then you have a memory leak. You should never, ever, ever write code that does this.

OTOH, if the user cancels the request (cancelling a CancellationToken), then the method will complete, possibly with an OperationCanceledException.

like image 164
Stephen Cleary Avatar answered Oct 23 '22 06:10

Stephen Cleary


It depends on the implementation of the Task returned by SomeMethod. The task is responsible for calling the continuation (ContinueWith), which will move execution forward. If the task never continued, you would have a memory leak. Most asynchronous APIs provide a timeout which would prevent this situation.

like image 45
Jesus Ruiz Avatar answered Oct 23 '22 05:10

Jesus Ruiz