forked from steffalk/AbstractIO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSample04ButtonControlsLampEventBased.cs
More file actions
47 lines (40 loc) · 1.8 KB
/
Sample04ButtonControlsLampEventBased.cs
File metadata and controls
47 lines (40 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Threading;
namespace AbstractIO.Samples
{
/// <summary>
/// Controls a lamp using a button without polling but using events (stemming from IRQs).
/// </summary>
public static class Sample04ButtonControlsLampEventBased
{
/// <summary>
/// The lamp to be controlled.
/// </summary>
private static IBooleanOutput _lamp;
public static void Run(IObservableBooleanInput button, IBooleanOutput lamp)
{
// Check arguments:
if (button == null) throw new ArgumentNullException(nameof(button));
if (lamp == null) throw new ArgumentNullException(nameof(lamp));
// Store the lamp so that the event handler can use it:
_lamp = lamp;
// Attach the event handler to the event that the button raises whenever it's Value changed:
button.ValueChanged += ButtonValueChangedHandler;
// Set the lamp to its initial state, as the event will raise not earlier than when the input changes:
lamp.Value = button.Value;
// Just wait and let the event handler react on button changes:
for (; ; ) Thread.Sleep(1000);
}
/// <summary>
/// Handles the <see cref="IObservableBooleanInput.ValueChanged"/> event.
/// </summary>
/// <param name="sender">The object which raised the event (that is, the button).</param>
/// <param name="newValue">The new value to which the button's <see cref="IBooleanInput.Value"/> property
/// changed.</param>
private static void ButtonValueChangedHandler(object sender, bool newValue)
{
// Turn the lamp on or off if the button was pressed or released, respectively:
_lamp.Value = newValue;
}
}
}