static Mutex mutex = new Mutex (false, "oreilly.com OneAtATimeDemo");
static void Main()
{
// Wait a few seconds if contended, in case another instance
// of the program is still in the process of shutting down.
if (!mutex.WaitOne (TimeSpan.FromSeconds (3), 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(); }
}
http://www.albahari.com/nutshell/ch20.aspxUso WaitOne() metodo
In questo codice:
if(mutex.WaitOne(TimeSpan.Zero, true))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
mutex.ReleaseMutex();
}
else
{
MessageBox.Show("only one instance at a time");
}
http://sanity-free.org/143/csharp_dotnet_single_instance_application.html
Non c'è inversione del if/bool.
Se waitone() è vero, vuol dire che un'istanza è già in esecuzione? Se viene restituito true, il thread corrente verrà bloccato, il che significherebbe che due processi che chiamano la stessa app si interromperanno entrambi?
La mia comprensione è la seguente:
// Don't block the thread while executing code.
//Let the code finish and then signal for another process to enter
Qual è l'implicazione di no! (restituendo true) e viceversa. O in altre parole, cosa succede in entrambi i modi?
So waitAll per esempio, aspetta che tutti i thread finiscano. Jon Skeet ha mostrato un buon esempio di questo sul suo sito, che è rimasto impressa nella mia mente (merito delle sue spiegazioni). Quindi ovviamente waitOne aspetta che un thread finisca. Il valore di ritorno è ciò che mi confonde.