简体   繁体   English

.NET 4.5中不完整的异步任务有什么影响?

[英]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: 假设您有一个Web处理程序,它调用这样的异步方法:

var foo = await SomeMethod();

And, due to poor coding (no CancellationToken, no timeouts, etc), SomeMethod never completes. 并且,由于编码不佳(没有CancellationToken,没有超时等), SomeMethod永远不会完成。 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. SomeMethod永远不会回来。 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. 如果SomeMethod永远不会完成,那么就会出现内存泄漏。 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 . OTOH,如果用户取消请求(取消CancellationToken ),则该方法完成,可能具有OperationCanceledException

It depends on the implementation of the Task returned by SomeMethod. 它取决于SomeMethod返回的Task的实现。 The task is responsible for calling the continuation (ContinueWith), which will move execution forward. 该任务负责调用continuation(ContinueWith),这将继续执行执行。 If the task never continued, you would have a memory leak. 如果任务从未继续,则会出现内存泄漏。 Most asynchronous APIs provide a timeout which would prevent this situation. 大多数异步API都会提供超时,以防止出现这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM