简体   繁体   中英

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

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?

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 .

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.

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