gpt4 book ai didi

c# - 调用多播委托(delegate)是否分配内存?

转载 作者:行者123 更新时间:2023-11-30 15:37:28 28 4
gpt4 key购买 nike

我们正在考虑重新设计我们的一些接口(interface),以使用 IObservable、Subject 和 Observer(后两者在 Reactive 扩展中)而不是标准的 .NET 事件。通过查看实现,我们发现 Subject 将锁定它需要回调的 IObserver 列表,然后创建一个新数组,将 IObserver 引用复制到该新数组中,然后调用它们。

当我们查看 MulticastDelegate 的实现时,我们可以看到 MulticastDelegate.GetInvocationList 的实现也创建了一个新数组,将要调用的委托(delegate)复制到该数组中,然后调用它们。不清楚的是,当您调用多播委托(delegate)时,GetInvocationList 是否被调用,或者它是否在框架内以不分配内存的方式进行处理。调用多播委托(delegate)是否会分配一个新数组?还是框架会处理一些事情,以便在引发事件时不会分配新数组?

我们的应用程序对内存分配和延迟非常敏感,因此我们试图通过迁移到新接口(interface)来确保不会为事件调用分配更多内存。我们还将在内部运行一些测试。

最佳答案

What is not clear is if when you invoke a multicast delegate GetInvocationList gets called or if it is handled within the framework in a way that does not allocate memory.

当您调用委托(delegate)时,它不会调用 GetInvocationList。这是用于处理和检查委托(delegate)的代码,而不是用于执行委托(delegate)的实际代码。运行时本身实际上在内部执行调用,因为它实际上不在 IL 中。这记录在 8.9.3 下的 CLI 规范中:

While, for the most part, delegates appear to be simply another kind of user-defined class, they are tightly controlled. The implementations of the methods are provided by the VES*, not user code.

基本上,实际调用由运行时在内部处理。

* VES == CLI 规范中的“虚拟执行系统”,该术语用于执行运行时本身的代码。

关于c# - 调用多播委托(delegate)是否分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12572560/

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