c# - 如果我在 c# 中注册一个事件,而它正在调度,我是否保证在该调度期间不会再次被调用?

标签 c# events mono

在 C# 中,我发现自己偶尔想在同一事件的调度过程中为该事件注册一个方法。例如,如果我有一个基于同一事件的连续分派(dispatch)来转换状态的类,我可能希望第一个状态的处理程序自行注销并注册第二个处理程序。但是,我不希望在下次触发事件之前分派(dispatch)第二个处理程序。

好消息是,Microsoft 的 C# 实现似乎正是以这种方式运行。事件注册语法糖被对 System.Delegate.Combine 的调用所取代,它只是将当前调用列表和新方法连接到一个单独的列表中,并将其分配给事件属性。这正是我想要的行为。

所以,我的问题是:语言标准是否保证了这种行为?我希望能够在其他平台上的单声道下运行我的 C# 代码,并且通常希望确保我不会根据其实现对语言标准做出假设。

我在 MSDN 上找不到任何确定的信息。

如果您想了解我所说内容的具体示例,请看这里:

    delegate void TestDelegate();
    static event TestDelegate TestEvent;

    static void Main (string[] args) {
        TestEvent += TestDelegateInstanceFirst;
        TestEvent();
        TestEvent();
    }

    static void TestDelegateInstanceFirst () {
        Console.WriteLine("First");
        TestEvent += TestDelegateInstanceSecond;
    }

    static void TestDelegateInstanceSecond () {
        Console.WriteLine("Second");
    }

至少在 Windows 上,输出是:

First
First
Second

最佳答案

是的,这是有保证的。

来自统一的 C# 3.0 规范,第 15.1 节:

However, when two non-null delegate instances are combined, their invocation lists are concatenated—in the order left operand then right operand—to form a new invocation list, which contains two or more entries.

注意“新调用列表”。在第 15.3 节中:

Once instantiated, delegate instances always refer to the same target object and method. Remember, when two delegates are combined, or one is removed from another, a new delegate results with its own invocation list; the invocation lists of the delegates combined or removed remain unchanged.

最后,System.Delegate 的 MSDN 指出:

Delegates are immutable; once created, the invocation list of a delegate does not change.

我怀疑 CLI 规范中有些东西 - 我会检查你是否愿意,但希望这三个给你足够的信心:)

关于c# - 如果我在 c# 中注册一个事件,而它正在调度,我是否保证在该调度期间不会再次被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/141423/

相关文章:

c# - 在我自己的页面中显示 ELMAH 错误详细信息?

c# - 在文本框/ block 中打印多行.net c#

c# - 如何以wpf形式捕捉窗口关闭按钮(窗口右上角的红色X按钮)事件?

c# - 前缀 "On"在 C# 编码中的事件案例中实现了什么?

c# - 为什么 Database.Query() 当空时返回 null?

c# - 如何使用 Unity3D 中的脚本让两个游戏对象面对面

c# - 防止 C# 中 HtmlButton 的回发

f# - Xbuild 构建面向 .NET 3.5 的 F# 3

wpf - 标准WPF选项卡控件中是否有Selected Tab Changed事件

c# - 为什么 Mono 源代码大部分是 C#?