2

使用 C# 构建了一个 Windows 服务来处理进入服务器的 .tif 文件。该服务工作正常,但会引发异常,然后继续根据需要处理文件。问题是我收到此错误:

System.IO.IOException:该进程无法访问该文件,因为它正被另一个进程使用。在 System.IO._Error.WinIOError (Int32 errorCode, String maybeFullPath) 在 System.IO。System.IO.File.Move 处的 _Error.WinIOError()(字符串源文件名,字符串 destFileName)

我相信我需要捕获异常、验证错误并显示消息“文件仍在处理中”但是,我不确定在哪里?我的 timer1 设置为 10 秒,这应该有足够的时间来处理文件。

我的代码:

protected void timer1Elapsed(object sender, EventArgs e)
    {
        try
        {
            if (mainProg == null)
            {
                mainProg = new ProcessFilesFromSource(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            }
            mainProg.ScanArchiverMain();          
        }
        catch (Exception ex)
        {
            EventLog.WriteEntry("ScanArchiver Error", ex.ToString());
            EventLog.WriteEntry("ScanArchiver Online");
        }            
      }
    protected override void OnStop()
    {
        EventLog.WriteEntry("ScanArchiver Offline");
        timer1.Enabled = false;
        timer1.Dispose();
    }
}
4

1 回答 1

0

处理过程中停止计时器,完成后重新启动。

还可以看看BackgroundWorker作为 Timer 的替代品。

protected void timer1Elapsed(object sender, EventArgs e)
    {
        timer1.Stop();
        try
        {

            if (mainProg == null)
            {
                mainProg = new ProcessFilesFromSource(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            }
            mainProg.ScanArchiverMain();          
        }
        catch (Exception ex)
        {
            EventLog.WriteEntry("ScanArchiver Error", ex.ToString());
            EventLog.WriteEntry("ScanArchiver Online");
        }            
        timer1.Start();
      }
于 2013-04-10T20:01:22.417 回答