Game Development Reference
In-Depth Information
This chapter presents a couple of ways to determine whether there is a running
instance of the application, pass command line arguments to an existing instance,
and bring its main window to the foreground.
Early Solutions
I have used a few strategies in the past to implement single application instances.
One method is to create a threading Mutex with a unique name that identifies the
application set to the full path to the executing assembly. The Mutex class can be
used to protect a shared resource from simultaneous access by multiple threads
and processes. A Mutex has two states: signaled or non-signaled. When the state is
signaled, the Mutex is not owned by any thread. When the state is non-signaled,
that means there is a thread that currently possesses ownership of the Mutex .The
ownership of a Mutex is only available to a single thread, so when two threads try
to write to the shared memory at the same time, the first thread to do so acquires
ownership, while the second thread waits for ownership to be released.
The first time an application starts up, it will perform a check for a uniquely
named Mutex to see if there are any other running instances. It will not find any, so
the next step will be to create a Mutex with a unique name so that other application
instances can see that another instance is already running; the unique name will be
the full system path to the executing assembly's location. With the Mutex created,
we must now call the WaitOne() method so that we set the state to non-signaled and
grant ownership to the thread of this application. At this point, the application
instance can completely load and make itself available to the end user.
All subsequent application instances that start up will perform the same check that
the first instance did, except they will fail. Each new instance will create a Mutex class
using the same name that the first instance used, but all further calls to WaitOne()
will return false because the ownership is currently bound to the thread of the first
The following code shows a simplified implementation using this approach.
using System.Threading;
static void Main()
Mutex mutex = new Mutex(false, Assembly.GetExecutingAssembly().Location);
if (!mutex.WaitOne(1, true))
Search Nedrilad ::

Custom Search