using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Model { public struct Timer { public long Id { get; set; } public long Time { get; set; } public TaskCompletionSource tcs; } [ObjectEvent] public class TimerComponentEvent : ObjectEvent, IUpdate { public void Update() { this.Get().Update(); } } public class TimerComponent: Component { private readonly Dictionary timers = new Dictionary(); /// /// key: time, value: timer id /// private readonly MultiMap timeId = new MultiMap(); private readonly EQueue timeoutTimer = new EQueue(); public void Update() { long timeNow = TimeHelper.Now(); foreach (long time in this.timeId.Keys) { if (time > timeNow) { break; } this.timeoutTimer.Enqueue(time); } while (this.timeoutTimer.Count > 0) { long key = this.timeoutTimer.Dequeue(); List timeOutId = this.timeId[key]; foreach (long id in timeOutId) { Timer timer; if (!this.timers.TryGetValue(id, out timer)) { continue; } timer.tcs.SetResult(true); } this.timeId.Remove(key); } } private void Remove(long id) { Timer timer; if (!this.timers.TryGetValue(id, out timer)) { return; } this.timers.Remove(id); } public Task WaitTillAsync(long tillTime, CancellationToken cancellationToken) { TaskCompletionSource tcs = new TaskCompletionSource(); Timer timer = new Timer { Id = IdGenerater.GenerateId(), Time = tillTime, tcs = tcs }; this.timers[timer.Id] = timer; this.timeId.Add(timer.Time, timer.Id); cancellationToken.Register(() => { this.Remove(timer.Id); }); return tcs.Task; } public Task WaitTillAsync(long tillTime) { TaskCompletionSource tcs = new TaskCompletionSource(); Timer timer = new Timer { Id = IdGenerater.GenerateId(), Time = tillTime, tcs = tcs }; this.timers[timer.Id] = timer; this.timeId.Add(timer.Time, timer.Id); return tcs.Task; } public Task WaitAsync(long time, CancellationToken cancellationToken) { TaskCompletionSource tcs = new TaskCompletionSource(); Timer timer = new Timer { Id = IdGenerater.GenerateId(), Time = TimeHelper.Now() + time, tcs = tcs }; this.timers[timer.Id] = timer; this.timeId.Add(timer.Time, timer.Id); cancellationToken.Register(() => { this.Remove(timer.Id); }); return tcs.Task; } public Task WaitAsync(long time) { TaskCompletionSource tcs = new TaskCompletionSource(); Timer timer = new Timer { Id = IdGenerater.GenerateId(), Time = TimeHelper.Now() + time, tcs = tcs }; this.timers[timer.Id] = timer; this.timeId.Add(timer.Time, timer.Id); return tcs.Task; } } }