Skip to content

Instantly share code, notes, and snippets.

@kipters
Created September 3, 2019 09:21
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 kipters/f4b6f4d939de11c67118350b9b50c0ec to your computer and use it in GitHub Desktop.
Save kipters/f4b6f4d939de11c67118350b9b50c0ec to your computer and use it in GitHub Desktop.
[Terrible Idea] Event handlers in initilizers
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