gpt4 book ai didi

singleton - 在 dotnet 核心中,如何确保我的应用程序只有一个副本在运行?

转载 作者:行者123 更新时间:2023-12-05 08:33:00 25 4
gpt4 key购买 nike

我以前做过这样的事情

private static bool AlreadyRunning()
{
var processes = Process.GetProcesses();
var currentProc = Process.GetCurrentProcess();
logger.Info($"Current proccess: {currentProc.ProcessName}");
foreach (var process in processes)
{
if (currentProc.ProcessName == process.ProcessName && currentProc.Id != process.Id)
{
logger.Info($"Another instance of this process is already running: {process.Id}");
return true;
}
}
return false;
}

效果很好。在新的 dotnet 核心世界中,所有东西都有一个名为 dotnet 的进程名称,所以我一次只能运行一个 dotnet 应用程序!不是我想要的 :D

在 dotnet 中是否有一种理想的方法来做到这一点?我看到建议的互斥体,但我不确定我是否理解在除 Windows 机器之外的其他系统上运行的可能缺点或错误状态。

最佳答案

.NET Core 现在支持全局命名互斥锁。来自 PR description ,添加了该功能:

  • On systems that support thread process-shared robust recursive mutexes, they will be used
  • On other systems, file locks are used. File locks, unfortunately, don't have a timeout in the blocking wait call, and I didn't find any other sync object with a timed wait with the necessary properties, so polling is done for timed waits.

此外,Named mutex not supported on Unix 中有一个有用的注释关于互斥锁名称的问题,应该使用:

By default, names have session scope and sessions are more granular on Unix (each terminal gets its own session). Try adding a "Global" prefix to the name minus the quotes.

关于singleton - 在 dotnet 核心中,如何确保我的应用程序只有一个副本在运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46302756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com