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

标签 singleton .net-core console-application mutex

我以前做过这样的事情

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/

相关文章:

c# - 将一个类绑定(bind)到多个接口(interface)作为单例

c++ - 优先考虑内存泄漏,以免减慢关机速度

android - 从 Play 控制台删除应用程序

.net - 为什么 Console.ReadKey() 会阻止在另一个线程中调用的 Console.WriteLine 的输出?

java - 让控制台等待用户输入关闭

Java多线程纠错——线程安全单例

java - 集群环境下的Spring单例

c# - 在 NET Core 中调用从 C++ 项目构建的 .dll 时出现 BadImageFormatException

.net - 通过 REST 在 DocumentDb 中创建文档时未经授权

C# 我可以使用部分类来使代码更具可读性吗