c# - 如果异步委托(delegate)调用永远不会返回会发生什么?

标签 c# .net asynchronous timeout delegates

我找到了一个看起来不错的示例,说明如何使用超时异步调用委托(delegate)... http://www.eggheadcafe.com/tutorials/aspnet/847c94bf-4b8d-4a66-9ae5-5b61f049019f/basics-make-any-method-c.aspx .总之,它使用带有超时的 WaitOne 来确定调用是否在超时到期之前没有返回。

我还知道您应该有一个 EndInvoke 来匹配每个 BeginInvoke。

那么如果等待超时到期会发生什么?我们(大概)不想调用 EndInvoke,因为那样会阻塞。代码可以继续做“其他事情”,但我们泄露了什么吗?是否有一些糟糕的线程在某个地方被阻塞等待永远不会发生的返回?我们是否在放置永不返回的结果的地方泄漏了一些内存?

最佳答案

我认为this帖子说得很好:

来自帖子:

You can't terminate an executing async delegate if it's not your thread, but you can if it is. If you use the common BeginInvoke type methods, you get a thread pool thread managed by the framework. If you use the Thread() class you get you own thread to manage, start, suspend, etc. as you like.

Developing asychronously requires that one decide who will manage the threads. The many different methods that execute asynchronously are using the ThreadPool threads behind the scenes.

Since you can't/shouldn't terminate a thread pool thread then you must design you code to communicate with the thread so that it can exit. The MSDN examples for the BackgroundWorker component demonstrates this kind of communication.

Sometimes your code may have the thread blocking waiting for IO. Here you would normally use a multiple object wait instead, waiting for IO or for a ManualResetEvent.

所以简而言之,如果有可能超时并且您希望线程结束,您将需要找到一种自己管理线程的方法。

关于c# - 如果异步委托(delegate)调用永远不会返回会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2998869/

相关文章:

c# - 是否可以在 C# MSScriptControl.ScriptControlClass 执行的 JScript 中休眠?

C# - "IsNullOrWhiteSpace"的反义词是什么?

c# - 为什么这个 C# ThreadPool 有时会丢弃工作项?

asynchronous - 如何在 flutter 应用程序中显示 5 分钟不可停止的计时器?

.NET 异步/等待任务在没有等待的情况下运行

c# - 为什么下面的代码是错误的?二项式系数

c# - 强制终结器顺序

c# - Include() ThenInclude() 在 Table Per Hierarchy 策略中抛出 "Sequence contains more than one matching element"异常

.net - 在未安装 Excel 的情况下以编程方式填充 Excel 模板

javascript - XMLHttpRequest 在保存时加载到调用对象