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.aspxSử dụng phương pháp
WaitOne() Trong mã này:
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
Không có đảo ngược của nếu/bool.
Nếu waitone() là đúng, điều đó có nghĩa là một cá thể đang chạy? Nếu true được trả về, luồng hiện tại sẽ bị chặn, điều đó có nghĩa là hai tiến trình gọi cùng một ứng dụng sẽ dừng lại?
hiểu biết của tôi là như sau:
// Don't block the thread while executing code.
//Let the code finish and then signal for another process to enter
ngụ ý của không là gì! (trở lại đúng) và ngược lại. Hay nói cách khác, chuyện gì sẽ xảy ra?
Tôi biết waitAll ví dụ, đợi tất cả các chuỗi kết thúc. Jon Skeet đã cho thấy một ví dụ điển hình về điều này trên trang web của anh ấy, vốn đã bị mắc kẹt trong tâm trí tôi (tín dụng cho lời giải thích của anh ấy). Vì vậy, rõ ràng waitOne chờ đợi cho một sợi để kết thúc. Giá trị trả về là điều làm tôi bối rối.