【问题标题】:Using Mutex to track another app's lifetime使用 Mutex 跟踪另一个应用程序的生命周期
【发布时间】:2017-11-19 21:11:11
【问题描述】:

MyApp1 (C#) 启动 MyApp2 (C#)。当 MyApp2 完全启动时,它会执行:

new Mutex(true, "MyApp2IsRunning");

与此同时,MyApp1 一直在等待这种情况发生,使用:

Mutex myApp2Mutex = null;
while (myApp2Mutex == null && !timedOut)
{
   try
   {
      myApp2Mutex = Mutex.OpenExisting("MyApp2IsRunning");
   }
   catch(WaitHandleCannotBeOpenedException)
   {
      Thread.Sleep(100);
   }
}
if (timedout) {return error;}
myApp2Mutex.WaitOne();

因此,如果 MyApp2 在分配的时间内启动,MyApp1 现在会等待 MyApp2IsRunning 互斥体以了解用户何时退出 MyApp2。

我只用 C++ 重写了 MyApp1。检测 MyApp2 状态的等效 Mutex 相关代码是什么?所以 MyApp1 仍将负责启动 MyApp2,我仍然希望它检测 MyApp2 何时启动以及用户何时退出 MyApp2。与上面相同的代码,但在 C++ 中。

【问题讨论】:

  • 太宽泛了。您可能想先在 Google 上搜索“mutex IPC”。
  • 使用 Windows API 互斥体。
  • @ChristianHackl 帖子太宽泛了怎么办?我认为我不能比提供我要移植的确切代码更具体。我不是 C++ 开发人员,所以谷歌搜索结果让我想知道 std::mutex 和其他选项之间的区别。

标签: c# c++ mutex


【解决方案1】:

一个简单的谷歌搜索给你:

HANDLE mutex_you_want = CreateMutex(nullptr, true, "MyApp2IsRunning");

【讨论】:

  • 让 App1 创建互斥锁并不能检测 App2 何时启动并准备就绪。
【解决方案2】:

此伪代码使 MyApp1 能够等待 MyApp2 启动,然后检测用户何时退出 MyApp2:

HANDLE hMutex = nullptr;
while (hMutex == nullptr && !timedout)
{
    hMutex = OpenMutex(
        SYNCHRONIZE,
        FALSE,
        "MyApp2IsRunning");
    Sleep(1000);
}
if (timedout){return error;}
DWORD wait_result = WaitForSingleObject(hMutex, INFINITE);

【讨论】:

    猜你喜欢
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    相关资源
    最近更新 更多