Reputation: 701
I've inherited a C# (.NET 2.0) app that has a bunch of static methods. I need to turn one of these methods into an asynchronous event-based method. When the method is complete, I want to fire off an event-handler. My question is, can I fire off an event handler from a static method? If so, how?
When I google, I only find IAsyncResult examples. 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 you!
Upvotes: 4
Views: 14884
Reputation: 67928
If the event
is declared in the type you're operating in you can pass in an instance (or recover it if it's a Singleton) and access the event
object from there. 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 were a singleton you could then 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 the Singleton accessor.
Upvotes: 0
Reputation: 91716
Provided DoStuffAsync
is static (which it wasn't in your code), the event myEvent_Completed
would also need to 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
would need to take an instance of your class to fire the event on:
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 needed different instances of your class to have different event handlers for this event, you'd want to go with the latter route and pass in an instance.
Other than that, there's absolutely nothing wrong with firing an event from a static method.
Upvotes: 3
Reputation: 29668
The process is exactly the same, the only difference is there isn't really a this
reference.
static EventHandler myEvent_Completed;
public void DoStuffAsync()
{
FireEvent();
}
private static void FireEvent()
{
EventHandler handler = myEvent_Completed;
if (handler != null)
handler(null, EventArgs.Empty);
}
Upvotes: 6