Using static methods with event handlers

I inherited a C # (.NET 2.0) application which has a bunch of static methods. I need to turn one of these methods into an event based async method. When the method is complete, I want to start the event handler. My question is, can I run an event handler from a static method? If so, how?

When I google I only find examples of IAsyncResult. However, I want to be able to do something like the following:

EventHandler myEvent_Completed;
public void DoStuffAsync()
{
  // Asynchrously do stuff that may take a while
  if (myEvent_Completed != null)
    myEvent_Completed(this, EventArgs.Empty);
} 

      

Thank!

+3


source to share


3 answers


The process is exactly the same, the only difference is that there is actually no link this

.



static EventHandler myEvent_Completed;

public void DoStuffAsync()
{
    FireEvent();
} 

private static void FireEvent()
{
    EventHandler handler = myEvent_Completed;

    if (handler != null)
        handler(null, EventArgs.Empty);
}

      

+4


source


If it DoStuffAsync

is static (which was not in your code), the event myEvent_Completed

must also be made static:

static EventHandler myEvent_Completed; // Event handler for all instances

public static void DoStuffAsync()
{
  // Asynchrously do stuff that may take a while
  if (myEvent_Completed != null)
    myEvent_Completed(null, EventArgs.Empty);
} 

      

Otherwise, DoStuffAsync

you will need to take an instance of your class to fire the event:



EventHandler myEvent_Completed; // Note: Can still be private

public static void DoStuffAsync(YourClass instance)
{
   // Asynchrously do stuff that may take a while
   if(instance.myEvent_Completed != null)
      instance.myEvent_Completed(instance, EventArgs.Empty);
}

      

If you want different instances of your class for different event handlers for that event, you need to go with the last route and pass the instance.

Also, there is nothing wrong with you triggering an event from a static method.

+3


source


If event

declared on the type you are working in, you can pass the instance (or restore it if it's a Singleton) and access the object event

. So for example:

EventHandler myEvent_Completed;
public void DoStuffAsync(MyClass o)
{
    // Asynchrously do stuff that may take a while
    if (o.myEvent_Completed != null)
        o.myEvent_Completed(this, EventArgs.Empty);
} 

      

If it was a singleton, you could do something like this:

EventHandler myEvent_Completed;
public void DoStuffAsync(MyClass o)
{
    // Asynchrously do stuff that may take a while
    if (Instance.myEvent_Completed != null)
        Instance.myEvent_Completed(this, EventArgs.Empty);
} 

      

where Instance

is a Singleton accessory.

0


source







All Articles