Limiting .NET Class to single object instance on c

2019-09-05 14:19发布

问题:

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#?

回答1:

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)...



回答2:

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.



回答3:

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