Skip to content

Instantly share code, notes, and snippets.

@govert
Last active December 1, 2017 22:06
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 govert/99b13368b1c1e78a5c9c77e43052f8ae to your computer and use it in GitHub Desktop.
Save govert/99b13368b1c1e78a5c9c77e43052f8ae to your computer and use it in GitHub Desktop.
Test code for Excel-DNA IExcelObservable
using System;
using System.Diagnostics;
using System.Threading;
using ExcelDna.Integration;
namespace TestDisposable
{
public static class RtdClock
{
[ExcelFunction(Description = "Provides a ticking clock")]
public static object TestObservable(string param)
{
string functionName = nameof(TestObservable);
object paramInfo = param; // could be one parameter passed in directly, or an object array of all the parameters: new object[] {param1, param2}
return ExcelAsyncUtil.Observe(functionName, paramInfo, () => new ExcelObservableClock(param));
}
}
class ExcelObservableClock : IExcelObservable
{
Timer _timer;
IExcelObserver _observer;
string _param;
public ExcelObservableClock(string param)
{
Debug.WriteLine("Created " + param);
_param = param;
_timer = new Timer(timer_tick, null, 0, 1000);
}
public IDisposable Subscribe(IExcelObserver observer)
{
_observer = observer;
observer.OnNext(DateTime.Now.ToString("HH:mm:ss.fff") + " (Subscribe)");
return new ActionDisposable(() =>
{
_observer = null;
Debug.WriteLine("Disposed " + _param);
});
}
void timer_tick(object _)
{
string now = DateTime.Now.ToString("HH:mm:ss.fff");
_observer?.OnNext(now);
}
class ActionDisposable : IDisposable
{
Action _disposeAction;
public ActionDisposable(Action disposeAction)
{
_disposeAction = disposeAction;
}
public void Dispose()
{
_disposeAction();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment