gpt4 book ai didi

c# - 我需要在 ManualResetEvent 上调用 Close() 吗?

转载 作者:可可西里 更新时间:2023-11-01 03:13:09 25 4
gpt4 key购买 nike

我一直在阅读 .NET 线程,并且正在编写一些使用 ManualResetEvent 的代码.我在互联网上找到了很多代码示例。但是,在阅读 WaitHandle 的文档时,我看到了以下内容:

WaitHandle implements the Dispose pattern. See Implementing Finalize and Dispose to Clean Up Unmanaged Resources.

似乎没有一个示例在它们创建的 ManualResetEvent 对象上调用 .Close(),即使是漂亮的 Recursion and Concurrency来自 pfxteam 博客的文章(编辑 - 这有一个我错过的 using block )。这只是示例疏忽,还是不需要?我很好奇,因为 WaitHandle“封装了特定于操作系统的对象”,因此很容易发生资源泄漏。

最佳答案

我最近收到了 C# 4.0 in a Nutshell: The Definitive Reference 的摘录作者:约瑟夫·阿尔巴哈里、本·阿尔巴哈里。在第 834 页的第 21 章:线程中有一节讨论了这一点。

Disposing Wait Handles

Once you’ve finished with a wait handle, you can call its Close method to release the operating system resource. Alternatively, you can simply drop all references to the wait handle and allow the garbage collector to do the job for you sometime later (wait handles implement the disposal pattern whereby the finalizer calls Close). This is one of the few scenarios where relying on this backup is (arguably) acceptable, because wait handles have a light OS burden (asynchronous delegates rely on exactly this mechanism to release their IAsyncResult’s wait handle).

Wait handles are released automatically when an application domain unloads.

关于c# - 我需要在 ManualResetEvent 上调用 Close() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2234128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com