|
| 1 | +using System; |
| 2 | +using System.Runtime.InteropServices; |
| 3 | + |
| 4 | +namespace Libuv { |
| 5 | + public class TimerWatcher : Watcher { |
| 6 | + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] |
| 7 | + public delegate void uv_timer_cb(IntPtr tmr, int status); |
| 8 | + [DllImport("uvwrap")] |
| 9 | + internal static extern IntPtr create_timer_watcher(uv_timer_cb cb, IntPtr myself); |
| 10 | + [DllImport("uvwrap")] |
| 11 | + internal static extern int uv_timer_init(IntPtr timer); |
| 12 | + [DllImport("uvwrap")] |
| 13 | + internal static extern int manos_timer_start(IntPtr timer, double after, double repeat); |
| 14 | + [DllImport("uvwrap")] |
| 15 | + internal static extern int uv_timer_stop(IntPtr timer); |
| 16 | + [DllImport("uvwrap")] |
| 17 | + internal static extern void uv_timer_again(IntPtr timer); |
| 18 | + [DllImport("uvwrap")] |
| 19 | + internal static extern void uv_timer_set_repeat(IntPtr timer, double time); |
| 20 | + private static uv_timer_cb unmanaged_callback; |
| 21 | + private Action<TimerWatcher, int> callback; |
| 22 | + private TimeSpan delay; |
| 23 | + private TimeSpan repeat; |
| 24 | + public TimeSpan Repeat { |
| 25 | + get { return repeat; } |
| 26 | + set { |
| 27 | + if (value < TimeSpan.Zero) |
| 28 | + throw new ArgumentException("value"); |
| 29 | + repeat = value; |
| 30 | + uv_timer_set_repeat(this.watcher, repeat.TotalMilliseconds); |
| 31 | + } |
| 32 | + } |
| 33 | + static TimerWatcher() |
| 34 | + { |
| 35 | + unmanaged_callback = StaticCallback; |
| 36 | + } |
| 37 | + public TimerWatcher(TimeSpan repeat, Action<TimerWatcher, int> callback) |
| 38 | + : this (TimeSpan.Zero, repeat, callback) |
| 39 | + { |
| 40 | + } |
| 41 | + public TimerWatcher(TimeSpan after, TimeSpan repeat, Action<TimerWatcher, int> callback) : base() |
| 42 | + { |
| 43 | + this.callback = callback; |
| 44 | + this.repeat = repeat; |
| 45 | + this.delay = after; |
| 46 | + watcher = create_timer_watcher(unmanaged_callback, GCHandle.ToIntPtr(gc_handle)); |
| 47 | + uv_timer_init(this.watcher); |
| 48 | + } |
| 49 | + private static void StaticCallback(IntPtr watcher, int status) |
| 50 | + { |
| 51 | + var handle = GCHandle.FromIntPtr(watcher); |
| 52 | + var watcher_instance = (TimerWatcher)handle.Target; |
| 53 | + watcher_instance.callback(watcher_instance, status); |
| 54 | + } |
| 55 | + public void Start() |
| 56 | + { |
| 57 | + manos_timer_start(this.watcher, delay.TotalMilliseconds, repeat.TotalMilliseconds); |
| 58 | + } |
| 59 | + public void Stop() |
| 60 | + { |
| 61 | + uv_timer_stop(this.watcher); |
| 62 | + } |
| 63 | + public void Again() |
| 64 | + { |
| 65 | + uv_timer_again(this.watcher); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments