How do I create a real-time Excel automation add-in in C# using RtdServer?

后端 未结 3 1032
梦谈多话
梦谈多话 2020-11-28 03:39

I was tasked with writing a real-time Excel automation add-in in C# using RtdServer for work. I relied heavily on the knowledge that I came across in Stack Overflow. I hav

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 03:56

    Calling UpdateNotify from the timer thread will eventually cause strange errors or disconnections from Excel.

    The UpdateNotify() method must only be called from the same thread that calls ServerStart(). It's not documented in RTDServer help, but it is restriction of COM.

    The fix is simple. Use DispatcherSynchronizationContext to capture the thread that calls ServerStart and use that to dispatch calls to UpdateNotify:

    public class RtdServer : IRtdServer
    {
        private IRTDUpdateEvent _rtdUpdateEvent;
        private SynchronizationContext synchronizationContext;
    
        public int ServerStart( IRTDUpdateEvent rtdUpdateEvent )
        {
            this._rtdUpdateEvent = rtdUpdateEvent;
            synchronizationContext = new DispatcherSynchronizationContext();
            _timer = new Timer(delegate { PostUpdateNotify(); }, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
            return 1;
        }
    
    
        // Notify Excel of updated results
        private void PostUpdateNotify()
        {
            // Must only call rtdUpdateEvent.UpdateNotify() from the thread that calls ServerStart.
            // Use synchronizationContext which captures the thread dispatcher.
            synchronizationContext.Post( delegate(object state) { _rtdUpdateEvent.UpdateNotify(); }, null);
        }
    
        // etc
    } // end of class
    

提交回复
热议问题