开发者

Design Pattern for Custom Events in .NET

What is the proper design pattern for cus开发者_如何学JAVAtom events in .NET (VB or C#).

Please note I am refering to custom events, where in you override the AddHandler, RemoveHander, and RaiseEvent methods.


1- Best practices for creating events is to do it the Microsoft's way, that is: the delegate takes 2 parameters, the first is the sender (who raises the event?) of type object, and arguments (additional information about the event) of type EventArgs or any derived type. Also don't return a value (void) from the event, and put all data you need in the 2nd argument. Check the example in this link.

2- Thread safety is another story, but you can start from these tips (from 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. 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜