如何测试是否已经在进行其他安装?
时间:2020-03-06 14:47:45 来源:igfitidea点击:
假设我正在尝试自动在Windows上安装某些软件,并且想尝试在尝试安装之前测试是否正在进行其他安装。我无法控制安装程序,因此必须在自动化框架中执行此操作。是否有更好的方法(某些Win32 API?)比仅测试msiexec是否正在运行?
[更新2]
改进了我以前用来直接访问互斥锁的先前代码,这更加可靠:
using System.Threading; [...] /// <summary> /// Wait (up to a timeout) for the MSI installer service to become free. /// </summary> /// <returns> /// Returns true for a successful wait, when the installer service has become free. /// Returns false when waiting for the installer service has exceeded the timeout. /// </returns> public static bool WaitForInstallerServiceToBeFree(TimeSpan maxWaitTime) { // The _MSIExecute mutex is used by the MSI installer service to serialize installations // and prevent multiple MSI based installations happening at the same time. // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx const string installerServiceMutexName = "Global\_MSIExecute"; try { Mutex MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName, System.Security.AccessControl.MutexRights.Synchronize); bool waitSuccess = MSIExecuteMutex.WaitOne(maxWaitTime, false); MSIExecuteMutex.ReleaseMutex(); return waitSuccess; } catch (WaitHandleCannotBeOpenedException) { // Mutex doesn't exist, do nothing } catch (ObjectDisposedException) { // Mutex was disposed between opening it and attempting to wait on it, do nothing } return true; }
解决方案
请参阅MSDN上_MSIExecute Mutex的描述。