Limit App to 1 Instance (Per File)?

M

Mario

I have a C# app that runs script files. The app is launched using a
command line argument to indicate which script should run. Most
scripts are run indefinitely in a loop and periodically perform tasks.
When the script is launched the Title Bar of the app indicates the name
of the app and the name of the script being run.

I thought to use a GetProcessesByName to return all instances of the
app and then to check the MainWindowTitle of each process to identify
that a script is running more than one instance. This almost works.
When the app is minimized, it runs in the system tray and the
MainWindowTitle returns and empty string.

While it is not difficult to prevent multiple instances of the app from
launching this is not the desired effect. The app may kick off any
number of instances. What matters is that the same script file is not
running under more than one instance of the app.

I realize I could record state information in a database or in a file
and check it upon launching the app, but there are timeliness issues
related to this approach -- the app may be too involved doing other
tasks to take the necessary time to update the state information for at
least several moments. Therefore, this approach is not
up-to-the-second accurate.

I considered checking scripts in and out. However, an abnormal
termination of the app may not properly check in a script as available.

Any ideas for making sure that only one instance of the app is running
any given script file?

Mario T. Lanza
Clarity Information Architecture, Inc.
2005.11
 
J

jeraldp

Mutex' are used across application boundaries. Right before running a
script, make sure you can create a mutex for it with a valid return.
When the script is complete, close the Mutex.

Something like this:

bool okToRun;
Mutex m = new Mutex(true, myScriptName, out okToRun);
if (okToRun)
{
// run script here
m.Close();
m = null;
}

-Jerry
 
B

Benny Raymond

You may want to also append the app name to "myScriptName" just to make
sure it's unique (incase a script has a name that is the same as some
other mutex on your machine). Something like this works well:

Mutex m = new Mutex(true, "appname" + myScriptName, out okToRun);
 
M

Mario

This is the first time I've heard anything about a "Mutex." I've just
now looked briefly into it and it seems like the right solution.
Thanks.
 
N

.neter

Maybe it's enough to open the script file and lock it (FileShare.None),
and close it after the script execution ends
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top