Created
September 3, 2019 09:21
-
-
Save kipters/f4b6f4d939de11c67118350b9b50c0ec to your computer and use it in GitHub Desktop.
[Terrible Idea] Event handlers in initilizers
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
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Threading; | |
namespace TerribleEventIdea | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var first = new TimerEventSource | |
{ | |
TickHandler = { FirstTicker } | |
}; | |
var second = new TimerEventSource | |
{ | |
TickHandler = { FirstMultiTicker, SecondMultiTicker } | |
}; | |
Thread.Sleep(Timeout.Infinite); | |
} | |
private static void SecondMultiTicker(object sender, int e) | |
{ | |
Console.WriteLine($"Second B: {e}"); | |
} | |
private static void FirstMultiTicker(object sender, int e) | |
{ | |
Console.WriteLine($"Second A: {e}"); | |
} | |
private static void FirstTicker(object sender, int e) | |
{ | |
Console.WriteLine($"First: {e}"); | |
} | |
} | |
public class TimerEventSource | |
{ | |
public event EventHandler<int> Tick; | |
public int Count { get; private set; } | |
private readonly Timer _timer; | |
public AddWrapper<EventHandler<int>> TickHandler { get; } | |
public TimerEventSource() | |
{ | |
_timer = new Timer(OnTick, null, 0, 1000); | |
TickHandler = new AddWrapper<EventHandler<int>>(action => Tick += action); | |
} | |
private void OnTick(object state) | |
{ | |
Count++; | |
Tick?.Invoke(this, Count); | |
} | |
} | |
public class AddWrapper<T> : IEnumerable<T> | |
{ | |
private readonly Action<T> _action; | |
public AddWrapper(Action<T> action) => _action = action; | |
public void Add(T value) => _action(value); | |
public void Add(IEnumerable<T> values) | |
{ | |
foreach (var value in values) | |
{ | |
_action(value); | |
} | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
throw new NotImplementedException(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
throw new NotImplementedException(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment