Skip to content

Instantly share code, notes, and snippets.

@OdeToCode
Created May 13, 2014 12:26
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 OdeToCode/e43279d671b7930018a4 to your computer and use it in GitHub Desktop.
Save OdeToCode/e43279d671b7930018a4 to your computer and use it in GitHub Desktop.
Subscribe and unsubscribe from events
public class Worker
{
public void StartWork()
{
for (var i = 0; i < 10; i++)
{
OnInterestingEvent();
Thread.Sleep(1000);
}
OnComplete();
}
public event EventHandler Complete;
public event EventHandler InterestingEvent;
protected virtual void OnComplete()
{
EventHandler handler = Complete;
if (handler != null) handler(this, EventArgs.Empty);
}
protected virtual void OnInterestingEvent()
{
EventHandler handler = InterestingEvent;
if (handler != null) handler(this, EventArgs.Empty);
}
}
public class TestEvents
{
public static void Main(string[] args)
{
_worker = new Worker();
_worker.InterestingEvent += HandleEvent;
_worker.Complete += Complete;
_worker.StartWork();
while (!_complete)
{
Thread.Sleep(500);
}
}
static void Complete(object sender, EventArgs e)
{
_complete = true;
}
private static void HandleEvent(object sender, EventArgs e)
{
_eventCount += 1;
Console.WriteLine(_eventCount);
if (_eventCount > 5)
{
_worker.InterestingEvent -= HandleEvent;
}
}
private static Worker _worker = null;
private static int _eventCount = 0;
private static bool _complete = false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment