Created
May 13, 2014 12:26
-
-
Save OdeToCode/e43279d671b7930018a4 to your computer and use it in GitHub Desktop.
Subscribe and unsubscribe from events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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