【问题标题】:Why AutoResetEvent and ManualResetEvent does not support name in the constructor?为什么 AutoResetEvent 和 ManualResetEvent 不支持在构造函数中命名?
【发布时间】:2010-05-12 07:28:13
【问题描述】:

在 .NET Framework 2.0 上,AutoResetEvent 和 ManualResetEvent 继承自 EventWaitHandle。 EventWaitHandle 类有 4 个不同的构造函数。 3 个构造函数支持为事件命名。另一方面,ManualResetEvent 和 AutoResetEvent 都不支持命名,并提供一个接收初始状态的构造函数。我可以简单地从 EventWaitHandle 继承并编写我自己的那些支持所有构造函数重载的类的实现,但如果我不需要的话,我不喜欢重新发明轮子。我的问题是:

  • 事件命名有什么特殊问题吗?
  • 你知道微软为什么不支持它吗?
  • 您有比从 EventWaitHandle 类继承并调用适当的构造函数(如下例所示)更好的建议吗?
公共类 MyAutoResetEvent:EventWaitHandle { 公共 MyAutoResetEvent(布尔初始状态) :基础(初始状态,EventResetMode.AutoReset) { } 公共 MyAutoResetEvent(布尔初始状态,字符串名称) :基础(初始状态,EventResetMode.AutoReset,名称) { } public MyAutoResetEvent(bool initialState, string name, out bool createdNew) : base(initialState, EventResetMode.AutoReset, name, out createdNew) { } public MyAutoResetEvent(bool initialState, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity) :基础(initialState,EventResetMode.AutoReset,string.Empty,out createdNew,eventSecurity) { } }

【问题讨论】:

    标签: multithreading .net-2.0 synchronization


    【解决方案1】:

    您可以像这样进行命名手动重置事件:

    // Open the event by name.
    EventWaitHandle namedMRSE = 
        new EventWaitHandle(false, EventResetMode.ManualReset, @"TheName");
    

    Here is the reference 用于上述代码。我不知道设计背后的具体原因,但 msdn 上的 there are some notes 表明存在基于应用程序域和流程的区别:

    事件等待句柄在许多情况下都很有用 相同的同步场景 作为监视器类。事件等待 手柄通常比 System.Threading.Monitor.Wait 和 System.Threading.Monitor.Pulse(System.Object) 方法,它们提供了更多的控制 过信号。命名事件等待 手柄也可用于 跨平台同步活动 应用领域和流程, 而监视器是本地的 应用领域。

    【讨论】:

    • 您的解决方案与我的解决方案类似。我从派生类的构造函数中调用EventWaitHandle,你直接使用。
    • @lkaso 我认为这比创建派生类更直接一些......不幸的是,我没有太多关于设计选择的原因。
    猜你喜欢
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多