问题描述
我创建了一个计时器
void Application_DocumentOpen(Microsoft.Office.Interop.Word.Document Doc)
{
System.Timers.Timer timer=new System.Timers.Timer(30000);
timer.Elapsed += (sender,e) => ExcelFileSendToAPI(Doc.FullName);
timer.Start();
}
ExcelFileSendToAPI 方法在文件打开后每 30 秒发出一次 api 请求。 没有任何问题 但是即使我打开 2 个 excel 应用程序并关闭一个 excel 应用程序,它也会继续在后台发出请求。 应用关闭后如何关闭定时器?
word、excel、powerpoint都存在这个问题。
解决方法
您需要在 timer_tick 函数而不是 Document_Open 函数中运行您的代码。我在您的另一个问题中为您提供了一个有效使用 timer_tick 事件的代码示例。
Timer Timer1 = new Timer();
void Application_DocumentOpen(Microsoft.Office.Interop.Word.Document Doc)
{
InitializeTimer();
}
void InitializeTimer()
{
Timer1.Interval = 30000;
Timer1.Tick += new EventHandler(Timer1_Tick);
}
private void Timer1_Tick (Object sender,EventArgs e)
{
DocumentEditingSendToServer(Doc.Application.ActiveDocument);
}
并且在您的 document_close 事件中,您需要停止计时器。