2017-02-21 55 views
-1

我有一个控制台应用程序不使用的代码终止保持控制台应用程序从关闭但仍运行代码

new System.Threading.AutoResetEvent(false).WaitOne(); 

我想达到的目标:我想运行一个StopWatch,如果它符合它会运行某些文件操作代码的条件。然后最后在代码块后,重置计时器并等待它重新运行再次true

问题:然而,调试后我无法让我的代码通过我的条件,即使它已经通过了所需的条件。

我的代码:

static void Main(string[] args) 
    { 
     string mutex_id = "41585f436f766572743243494d"; 
     using (System.Threading.Mutex mtx = new System.Threading.Mutex(false, mutex_id)) 
     { 
      if(!mtx.WaitOne(0,false)) 
      { 
       return; 
      } 
      processTimer = new Stopwatch(); 
      processTimer.Start(); 

      if (processTimer.Elapsed.Seconds > 10) 
      { 
       processTimer.Stop(); 
       fileQueue = Directory.GetFiles(ConfigurationManager.AppSettings["WatchPath"], ConfigurationManager.AppSettings["Format"]).ToList(); 
      } 
      //process the fileQueue 
      //.. 
      //.. 
      //processTimer.Reset(); -> Reset Timer to wait for another 10 sec and process again 
      new System.Threading.AutoResetEvent(false).WaitOne(); 
     } 
    } 

我从前使用过FileSystemWatcher,但我没能得到正确的过程(如同连续/并行文件创建和这样)。尝试ThreadingTimers作为我的question

现在我试图从新的角度来处理这个问题。希望有些人能够用这个来启发我。

+0

为什么要使用['StopWatch'](https://msdn.microsoft.com/en-us/library/ system.diagnostics.stopwatch(v = vs.110).aspx),而不是说[[Timer]](https://msdn.microsoft.com/en-us/library/system.threading.timer(v = vs.110)的.aspx)? –

回答

2

代码中没有“再试一次”。

你写的代码执行以下操作:

  1. 创建一个互斥体并锁定
  2. 如果它已经存在,关闭应用
  3. 启动秒表
  4. 检查如果在10秒过去(他们没有)
  5. 创建一个新的AutoResetEvent和等待它

你需要一些循环如果在10秒已通过定期检查和否则Sleep

+0

几个小时前就知道了。只是做了一个无限的'while'循环并且做事情。不管怎样,谢谢。 – Hexxed

相关问题