开发者

How do static events compare to non-static events in C#?

I just realized static events exist - and I'm curious how people use them. I wonder how the relative comparison holds up to static vs. instance methods. For instance, a static method is basically a global function. But I've always associated events with instances of objects and I'm having trouble thinking of them at the global level.

Here some code to refer to if it helps an explanation:

void Main()
{
    var c1 = new C1();
    c1.E1 += () => Console.WriteLine ("E1");
    C1.E2 += () => Console.WriteLine ("E2");
    c1.F1();
}

// <<delegate>>+D()
public delegate void D();

// +<<event>>E1
// +<<class>><<event>>E2
// +F()
//      <<does>>
//          <<fire>>E1
//          <<fire>>E2
public class C1
{
    public void F1()
    {
        OnE1();
        OnE2();
    }
    public event D E1;
    private void OnE1()
    {
        if(E1 != null)
        {
            E1();
        }
    }
    static public event D E2;
    static private void OnE2()
    {
        if(E2 != null)
        开发者_JAVA技巧{
            E2();
        }
    }
}


Be wary of static events. Remember that, when an object subscribes to an event, a reference to that object is held by the publisher of the event. That means that you have to be very careful about explicitly unsubscribing from static events as they will keep the subscriber alive forever, i.e., you may end up with the managed equivalent of a memory leak.


Much of OOP can be thought of in terms of message passing.

A method call is a message from the caller to the callee (carrying the parameters) and a message back with the return value.

An event is a message from the source to the subscriber. There are thus potentially two instances involved, the one sending the message and the one receiving it.

With a static event, there is no sending instance (just a type, which may or may not be a class). There still can be a recipient instance encoded as the target of the delegate.


In case you're not familiar with static methods

You're probably already familiar with static methods. In case you're not, An easy-to-understand difference is that you don't need to create an instance of an object toi use a static method, but you DO need to create an instance of an object to call a non-static method.

A good example is the System.IO.Directory and System.IO.DirectoryInfo classes.

The Directory class offers static methods, while the DirectoryInfo class does not.

There are two articles describing them here for you to see the difference for yourself.

http://visualcsharptutorials.com/2011/01/system-io-directory-class/

http://visualcsharptutorials.com/2011/01/system-io-directoryinfo-class/

Now on to static events...

However, static events are seldom seen in the wild. There are very few cases that I can think opf where I'd actually want to use one, but there is a CodeProject article that does show one potential use.

http://www.codeproject.com/KB/cs/staticevent.aspx

The key thought here is taken from the explanation (bold added by me to point out the relevant text):

We saw this property as a separate object and we made sure that there is only one instance of it at a time. And all instances of transactions knew where to find it when needed. There is a fine difference though. The transactions will not need to know about the changes happening on the exchange rate, rather they will use the last changed value at the time that they use it by requesting the current value. This is not enough when, for example, we want to implement an application where the user interface reacts immediately on changes in the UI characteristics like font, as if it has to happen at real-time. It would be very easy if we could have a static property in the Font class called currentFont and a static method to change that value and a static event to all instances to let them know when they need to update their appearance.

As .NET developers we're trained to work with a disconnected model. Think of ADO.NET compared to classic ADO. IN a VB6 app, you could use data controls that would allow the following functionality: If you were running the app on your PC, the data in your grid would update when someone on another PC edited the data.

This isn't something that .NET developers are used to. We're very used to the disconnected model. Static events enable a more "connected" experience. (even if that experience is something we're not used to any more.)


for some insight check this link http://www.codeproject.com/KB/cs/staticevent.aspx

static event can be used

  • when no instance exists
  • to do some multicast event for all existing instances...
  • when you have a static class which can fire events...

BUT one should use them with cuation... see discussion http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/2ac862f346b24a15/8420fbd9294ab12a%238420fbd9294ab12a?sa=X&oi=groupsr&start=1&num=2

more info

http://msdn.microsoft.com/en-us/library/8627sbea.aspx
http://dylanbeattie.blogspot.com/2008/05/firing-static-events-from-instance.html
http://www.nivisec.com/2008/09/static-events-dont-release.html


Static members are not "global," they are simply members of the class, not of class instances. This is as true for events as it is for methods, properties, fields, etc.

I can't give an example for using a static event, because I generally don't find static members to be useful in most cases. (They tend to hint at anti-patterns, like Singleton.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜