0

我想让同一台计算机上的多个进程使用某个 .NET 类的一个对象。

有了应用程序域,就不太可能跨越该边界,但 .NET 4.0 中的内存映射文件应该以某种方式简化该任务。

在 .NET 4.0 最终版本发布之前......是否可以在 C# 中制作某种“进程间单例”?

4

3 回答 3

4

是的,您可以在一个进程中创建一个 .Net Remoting 单例,并通过 Remoting 将其公开给在同一台机器上运行的其他进程...

编辑:在 .Net 2.x 中,您需要使用 Remoting 解决方案,但在 .Net 3.x 或更高版本(WCF 可用)中,可以使用 WCF 获得相同的功能检查一下)...

于 2009-08-08T19:59:31.530 回答
2

您可能想要使用全局互斥锁。

C# 中的线程有一个很好的示例(为方便起见,复制如下),说明如何使用命名互斥锁来确保只有一个应用程序实例可以在机器上运行。

您可以扩展此示例以确保也只有一个对象实例。

class OneAtATimePlease {
  // Use a name unique to the application (eg include your company URL)
  static Mutex mutex = new Mutex (false, "oreilly.com OneAtATimeDemo");

  static void Main() {
    // Wait 5 seconds if contended – in case another instance
    // of the program is in the process of shutting down.

    if (!mutex.WaitOne (TimeSpan.FromSeconds (5), false)) {
      Console.WriteLine ("Another instance of the app is running. Bye!");
      return;
    }
    try {
      Console.WriteLine ("Running - press Enter to exit");
      Console.ReadLine();
    }
    finally { mutex.ReleaseMutex(); }
  }
}

您可能还需要注意一件事。

在终端服务中运行的服务器上使用命名互斥锁时,命名互斥锁可以具有两个级别的可见性,全局对所有会话(名称前缀为“ Global\”)或本地到终端服务器会话(名称前缀为“ Local\”,如果没有指定前缀,它将是默认值)。

您可以在MSDN:Mutex Class中找到有关 Mutex 的更多详细信息。

于 2009-08-08T20:39:23.993 回答
0

Install your .net dll in the global assembly cache. Then it can be referenced by any application on the computer.

于 2009-10-26T20:52:48.200 回答