// ============================================================================= // B28 English — RTD real-time-data server (MyRtdServer.cs) // B28 英文版 — RTD 实时数据服务器(MyRtdServer.cs) // ============================================================================= // // Key points: // 1. MUST inherit ExcelDna.Integration.Rtd.ExcelRtdServer // 2. Must override (all mandatory): // - protected override bool ServerStart() parameter-less // - protected override object ConnectData(Topic topic, IList topicInfo, ref bool newValues) // - protected override void DisconnectData(Topic topic) // - GetActiveTopics() is a PROTECTED instance method (not override) — use it when pushing updates // 3. ServerStart / ConnectData signatures are NOT frozen across versions; check the docs of your version. // ============================================================================= using ExcelDna.Integration; using ExcelDna.Integration.Rtd; // RTD types (ExcelRtdServer, Topic) using System.Timers; using System.Collections.Generic; namespace MyExcelAddIn { /// /// Real-time data server: pushes a new random value to all subscribers every second. /// public class MyRtdServer : ExcelRtdServer { private Timer _timer; // .NET built-in timer private double _lastValue = 0; // latest value // ------------------------------------------------------------------------- // Server start: invoked by Excel-DNA when this RTD is loaded (parameter-less). // Return true to indicate success. // ------------------------------------------------------------------------- protected override bool ServerStart() { _timer = new Timer(1000); // Trigger every 1000 ms (1 second) _timer.Elapsed += (s, e) => { // Mock data: random number in [0, 100) every second. _lastValue = new System.Random().NextDouble() * 100; // Push the latest value to all active topics. foreach (Topic topic in GetActiveTopics()) { topic.UpdateValue(_lastValue); // Tell Excel: please refresh. } }; _timer.Start(); return true; } // ------------------------------------------------------------------------- // Server terminate: invoked when Excel unloads; do cleanup. // ------------------------------------------------------------------------- protected override void ServerTerminate() { _timer?.Stop(); _timer?.Dispose(); _timer = null; } // ------------------------------------------------------------------------- // Excel calls this when a topic is first subscribed; return the initial value. // ------------------------------------------------------------------------- protected override object ConnectData(Topic topic, IList topicInfo, ref bool newValues) { newValues = true; return _lastValue; } // ------------------------------------------------------------------------- // Excel calls this when a topic is unsubscribed; usually a no-op. // ------------------------------------------------------------------------- protected override void DisconnectData(Topic topic) { // no-op } } }