Skip to content

Instantly share code, notes, and snippets.

@vendettamit
Created June 6, 2013 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vendettamit/5721958 to your computer and use it in GitHub Desktop.
Save vendettamit/5721958 to your computer and use it in GitHub Desktop.
Check if the event is hooked with the Handler
public static void Usage()
{
var instance = new Timer();
// check if the event is assigned a handler
if (GetEventHandler(instance, "Elapsed", "ElapsedEventHandler") == null)
{
throw new InvalidOperationException(string.Format("The Timer elapsed event must be assigned an event handler. Source: {0}", type.FullName));
}
}
/// <summary>
/// Gets the event handler.
/// </summary>
/// <param name="classInstance">The class instance.</param>
/// <param name="eventName">Name of the event.</param>
/// <returns></returns>
static ElapsedEventHandler GetEventHandler(Timer classInstance, string eventName, string eventHandler)
{
ElapsedEventHandler eventDelegate = null;
Type classType = classInstance.GetType();
var eventField = classType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
var handler = eventField.FirstOrDefault(x => (x.FieldType.Name == eventHandler));
if (handler != null)
{
eventDelegate = (ElapsedEventHandler)handler.GetValue(classInstance);
}
return eventDelegate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment