通过互斥体限制窗口进程?

问题描述 投票:0回答:0

我有一个 Windows 控制台应用程序,它正在查询数据库中的一个表。传递到控制台应用程序的参数包括一个连接字符串和一个在数据库的特定表中找到的值。这个控制台应用程序可以随时启动。

我希望只允许一个进程为该列中的每个值运行。因此,如果进程 A 针对 db A 和值 B 启动,然后不久之后,进程 B 针对 db A 和值 B 启动,那么进程 A 将完成其工作,进程 B 将优雅地终止(!),因为另一个进程是已经完成了它本应完成的工作。如果进程 B 有不同的数据库或不同的值,那么应该允许它启动。

我一直在使用互斥锁来尝试实现这一点,但是当它们应该优雅地退出时,我仍然在运行多个进程。

这是我的代码中关于如何创建互斥体的一个例子:

`    
 private static Mutex _mutex;

 static void Main(string[] args)
 {           
     try
     {                
         var settings = Switches(args);   
         if (settings.TryGetValue("db", out string db))
         {        
             if (TryGetConnection(settings, out string cx))
             {
                 if (settings.TryGetValue("value", out string value))
                 {                                                         
                     var owned = false;
                     // create name for mutex including the db and table value
                     //so that other processes using the same db and table value
                     //will not be able to acquire the mutex and start processing
                     var mutexName = MutexName(cx, value);                      
                     using (_mutex = new Mutex(false, mutexName, out owned))
                     {
                         if (owned)
                         {
                             // wait up to 10 secs to get mutex
                             var mutexAcquired = _mutex.WaitOne(10000);
                             if (mutexAcquired)
                             {
                                 ... do work here

                                 _mutex.ReleaseMutex();
                             }
                             else
                             { 
                                 return;
                             }
                         }
                         else
                         {                          
                             return;
                         }                            
                     }                   
                 }
             }
         }
     }
     catch (Exception ex)
     {
        ...
     }       
}`

也许这不是实现我所追求目标的最佳方式。

如果有人可以通过纠正我所做的事情或提出更好的方法来引导我朝着正确的方向前进,我将不胜感激?谢谢

我已经尝试过关于互斥体的各种建议,但没有一个从开始就停止了具有相同参数的第二个进程

c# process mutex
© www.soinside.com 2019 - 2024. All rights reserved.