在多線程中觸發事件可能拋出引用為空的異常,這個問題網上有很多論述。
NetworkComms通信框架本身幾乎沒有使用事件,所以在核心通信框架中不存在這個問題。
在網上查了很多資料,比如下面這個:
我們采用的方案:
public static class Extensions { public static void Raise<T>(this EventHandler<T> handler, object sender, T args) where T : EventArgs { if (handler != null) handler(sender, args); } }
定義事件如下:
//包含文件信息的事件參數 public class FileEventArgs : EventArgs { public FileEventArgs(FileDetail fileInfo) { FileInfo = fileInfo; } public FileDetail FileInfo { get; set; } }
public event EventHandler<FileEventArgs> NewDoubleClick;
觸發事件語句:
NewDoubleClick.Raise(this,new FileEventArgs(this.FileInfo));
參考文章
http://stackoverflow.com/questions/786383/c-sharp-events-and-thread-safety
http://stackoverflow.com/questions/840715/the-proper-way-of-raising-events-in-the-net-framework
http://stackoverflow.com/questions/9033/hidden-features-of-c/9282#9282
http://stackoverflow.com/questions/840715/the-proper-way-of-raising-events-in-the-net-framework
http://stackoverflow.com/questions/231525/raising-c-sharp-events-with-an-extension-method-is-it-bad
http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx
http://stackoverflow.com/questions/786383/c-sharp-events-and-thread-safety
http://codeblog.jonskeet.uk/2015/01/30/clean-event-handlers-invocation-with-c-6/
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3796170-add-raise-extension-method-for-eventhandler-and
www.cnblogs.com/networkcomms
www.networkcomms.cn