Limiting .NET Class to single object instance on c

2019-09-05 14:15发布

I want to have one object of some .NET class used by multiple processes on same computer.

Having Application domains, it is not easily possible to move across that boundary, but memory-mapped files in .NET 4.0 should ease that task in some way.

Until .NET 4.0 comes in final release... Is it possible to make some kind of "inter-process singleton" in C#?

3条回答
贪生不怕死
2楼-- · 2019-09-05 14:54

Yes you can create a .Net Remoting singleton in one process, and expose it to the other processes running on the same machine via Remoting...

EDIT: in .Net 2.x, you need to use a Remoting solution, but in .Net 3.x or later (wherer WCF is Available) this same funcctionality may be available using WCF (Check it out)...

查看更多
男人必须洒脱
3楼-- · 2019-09-05 15:06

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

查看更多
成全新的幸福
4楼-- · 2019-09-05 15:09

You may want to use global mutex.

Threading in C# has a nice example (copied below for convenience) on how to use named mutex to enusure only one instance of an application can run on a machine.

You can expand this example to ensure there is only one instance of an object as well.

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(); }
  }
}

There is one more thing you may need to pay attention.

When using named mutex on a server that is running in terminal services, a named mutex can have two level of visibility, Global to all the sessions (name prefixed with "Global\") or Local to the terminal server session (name prefixed with "Local\", it will be default if no prefix is specified).

You can find more details on Mutex in MSDN: Mutex Class.

查看更多
登录 后发表回答