gpt4 book ai didi

c# - .NET 中自定义事件的设计模式

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:39 24 4
gpt4 key购买 nike

.NET(VB 或 C#)中自定义事件的正确设计模式是什么。

请注意,我指的是自定义事件,您可以在其中覆盖 AddHandler、RemoveHander 和 RaiseEvent 方法。

最佳答案

1- 创建事件的最佳实践是按照 Microsoft 的方式进行,即:委托(delegate)采用 2 个参数,第一个是对象类型的发送者(谁引发事件?),以及参数(关于事件的附加信息event) 类型 EventArgs 或任何派生类型。也不要从事件中返回值(void),并将您需要的所有数据放在第二个参数中。检查example in this link .

2- 线程安全是另一回事,但您可以从这些提示(来自 MSDN)开始:

In general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this guideline:

* lock (this) is a problem if the instance can be accessed publicly.

* lock (typeof (MyType)) is a problem if MyType is publicly accessible.

* lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

example:

Object thisLock = new Object(); 
lock(thisLock)
{
// Critical code section.
}

关于c# - .NET 中自定义事件的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2305198/

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