如何从一个静态类引发自定义事件 [英] How to raise custom event from a Static Class
问题描述
我有一个静态类,我想提出一个事件作为类的静态方法中的一个try catch块的一部分。
I have a static class that I would like to raise an event as part of a try catch block within a static method of that class.
例如在这个方法我想提出在catch自定义事件。
For example in this method I would like to raise a custom event in the catch.
public static void saveMyMessage(String message)
{
try
{
//Do Database stuff
}
catch (Exception e)
{
//Raise custom event here
}
}
感谢您。
推荐答案
重要提示:非常小心的情况下订阅一个静态的事件。静态到静态是好的,但是从静态事件到一个实例句柄的订阅是一个伟大的(阅读:非常危险)的方式来保持该实例永远活着。 GC将看到该链接,除非你取消(或使用像一个WeakReference的)不会收集实例。
Important: be very careful about subscribing to a static event from instances. Static-to-static is fine, but a subscription from a static event to an instance handler is a great (read: very dangerous) way to keep that instance alive forever. GC will see the link, and will not collect the instance unless you unsubscribe (or use something like a WeakReference).
有关创建静态事件的模式是一样的isntance事件,只需用静态
:
The pattern for creating static events is the same as isntance events, just with static
:
public static event EventHandler SomeEvent;
为使生活更轻松(空重检查),这里有用的技巧是添加一个简单的处理程序:
To make life easier (re null checking), a useful trick here is to add a trivial handler:
public static event EventHandler SomeEvent = delegate {};
然后,你可以简单地调用它没有空检查:
Then you can simply invoke it without the null-check:
SomeEvent(null, EventArgs.Empty);
请注意,由于委托实例是不可改变的,和去引用是线程安全的,从来就没有在这里比赛状态,无需锁定...谁的一次,当我们去参考被调用订阅。
Note that because delegate instances are immutable, and de-referencing is thread-safe, there is never a race condition here, and no need to lock... who-ever is subscribed when we de-reference gets invoked.
(调整自己的事件,ARGS等)。
这招同样适用于实例的事件。
(adjust for your own event-args etc). This trick applies equally to instance events.
这篇关于如何从一个静态类引发自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!