How to expose an event in a c# class?
I am building a simple class to开发者_开发知识库 hold related methods. Part of this code includes synchronising to a database. The built in SyncOrchestrator
class includes a SessionProgress event handler which I can wire up an event to.
What I would like to do is instance my class and then hook up an some code to this event so that I can display a progress bar (ill be using BGWorker).
So, my question is probably c# 101, but how do I expose this event through my class the correct way so that I can wire it up?
Thanks
I think you're looking for something like this:
(I also suggest you read the Events tutorial on MSDN.)
public class SyncOrchestrator
{
// ...
public event EventHandler<MyEventArgs> SessionProgress;
protected virtual void OnSessionProgress(MyEventArgs e)
{
// Note the use of a temporary variable here to make the event raisin
// thread-safe; may or may not be necessary in your case.
var evt = this.SessionProgress;
if (evt != null)
evt (this, e);
}
// ...
}
where the MyEventArgs
type is derived from the EventArgs
base type and contains your progress information.
You raise the event from within the class by calling OnSessionProgress(...)
.
Register your event handler in any consumer class by doing:
// myMethodDelegate can just be the name of a method of appropiate signature,
// since C# 2.0 does auto-conversion to the delegate.
foo.SessionProgress += myMethodDelegate;
Similarly, use -=
to unregister the event; often not explicitly required.
Like this:
public event EventHandlerDelegate EventName;
EventHandlerDelegate
should obviously be the name of a delegate type that you expect people to provide to the event handler like so:
anObject.EventName += new EventHandlerDelegate(SomeMethod);
When calling the event, make sure you use this pattern:
var h = EventName;
if (h != null)
h(...);
Otherwise you risk the event handler becoming null
in between your test and actually calling the event.
Also, see the official documentation on MSDN.
精彩评论