如何让C#计时器在创建它的同一个线程上执行?

时间:2012-12-06 06:22:51

标签: c# .net multithreading timer

我想在Excel Addin上启用IMessageFilter我必须写入excel。 我从here的例子中得到了例子:

  

消息过滤器是每个线程的,所以我们将此线程注册为   消息过滤器(不是创建加载项的主线程 -   因为那是Excel的主要线程

我的问题是,当计时器过去时,我的系统会写入excel,这会导致从ThreadPool线程调用写入方法,该线程会中断IMessageFilter,因为excel无法访问RetryRejectedCall IMessageFilter部分1}},因为它存在于调用者线程而不是由计时器产生的执行线程。

所以,我的问题是:有没有办法可以强制计时器的Elapsed事件在初始化计时器的同一个线程上运行?

  

编辑:

我的问题是,如何在IMessageFilter抛出拒绝/忙碌时抓住excel错误?

THX

2 个答案:

答案 0 :(得分:7)

您可以使用Timer.SynchronizingObject属性来封送在间隔过去时发出的事件处理程序调用。

来自MSDN

  

当Elapsed事件由可视Windows窗体组件处理时,   例如按钮,通过系统线程访问组件   池可能会导致异常或者可能无法正常工作。避免这样做   通过将SynchronizingObject设置为Windows窗体组件,   这会导致调用处理Elapsed事件的方法   与创建组件的线程相同。

假设您正在使用WinFrom,并且您正在主窗体中创建计时器实例:

System.Timers.Timer t = new System.Timers.Timer();
t.SynchronizingObject = this;
t.Elapsed += t_Elapsed;
t.Start();

答案 1 :(得分:3)

完整的答案如下:

问题:将数据写入excel的类无法处理来自excel的“忙/拒绝”响应消息。

解决方案:按照here

所述实施IMessageFilter界面

IMessageFilter定义(来自链接):

namespace ExcelAddinMessageFilter
{
        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct INTERFACEINFO
        {
            [MarshalAs(UnmanagedType.IUnknown)]
            public object punk;
            public Guid iid;
            public ushort wMethod;
        }

        [ComImport, ComConversionLoss, InterfaceType((short)1),
        Guid("00000016-0000-0000-C000-000000000046")]
        public interface IMessageFilter
        {
            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall,
                MethodCodeType = MethodCodeType.Runtime)]
            int HandleInComingCall([In] uint dwCallType, [In] IntPtr htaskCaller,
                [In] uint dwTickCount,
                [In, MarshalAs(UnmanagedType.LPArray)] INTERFACEINFO[]
                lpInterfaceInfo);

            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall,
                MethodCodeType = MethodCodeType.Runtime)]
            int RetryRejectedCall([In] IntPtr htaskCallee, [In] uint dwTickCount,
                [In] uint dwRejectType);

            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall,
                MethodCodeType = MethodCodeType.Runtime)]
            int MessagePending([In] IntPtr htaskCallee, [In] uint dwTickCount,
                [In] uint dwPendingType);
        }
    }

IMessageFilter我班级的实施部分(见链接):

#region IMessageFilter Members

        int ExcelAddinMessageFilter.IMessageFilter.
            HandleInComingCall(uint dwCallType, IntPtr htaskCaller, uint dwTickCount, ExcelAddinMessageFilter.INTERFACEINFO[] lpInterfaceInfo)
        {
            // We're the client, so we won't get HandleInComingCall calls.
            return 1;
        }

        int ExcelAddinMessageFilter.IMessageFilter.
        RetryRejectedCall(IntPtr htaskCallee, uint dwTickCount, uint dwRejectType)
        {
            // The client will get RetryRejectedCall calls when the main Excel
            // thread is blocked. We can handle this by attempting to retry
            // the operation. This will continue to fail so long as Excel is 
            // blocked.
            // As an alternative to simply retrying, we could put up
            // a dialog telling the user to close the other dialog (and the
            // new one) in order to continue - or to tell us if they want to
            // abandon this call
            // Expected return values:
            // -1: The call should be canceled. COM then returns RPC_E_CALL_REJECTED from the original method call.
            // Value >= 0 and <100: The call is to be retried immediately.
            // Value >= 100: COM will wait for this many milliseconds and then retry the call.
            return 1;
        }

        int ExcelAddinMessageFilter.IMessageFilter.
            MessagePending(IntPtr htaskCallee, uint dwTickCount, uint dwPendingType)
        {
            return 1;
        }

        #endregion

通过定义和实施IMessageFilter接口,我按如下方式设置了STA ThreadTimers.Timer

主题:

thread = new Thread(WriteToExcel);
thread.SetApartmentState(ApartmentState.STA);

计时器:

timer = new System.Timers.Timer();
timer.Interval = 2000;
timer.Elapsed += new ElapsedEventHandler(StartSTAThread_Handler);

其中StartSTAThread_Handler定义为:

void StartSTAThread_Handler(object source, ElapsedEventArgs e)
{
     thread.Start();
     thread.Join();
     thread = null;
}

此线程调用我用于写入Excel的方法,并使用上述IMessageFilter接口处理被拒绝的消息。我要做的最后一件事就是完全符合excel OM参考资格,即;而不是:

Excel.Range rng = app.ActiveSheet.Range["range_name"];
rng.Copy(); // ERRROR: message filter's RetryRejectedCall is NOT called

我必须使用完全限定的引用:

app.ActiveSheet.Range["range_name"].Copy // OK: calls RetryRejectedCall when excel dialog etc is showing

虽然这似乎符合我的需要,但似乎与另一张海报here所描述的“双点规则”相矛盾......