Mutex
http://www.albahari.com/threading/part2.aspx#_Mutex
A Mutex
is like a C# lock
, but it can work across multiple processes.
In other words, Mutex
can be computer-wideas well as application-wide.
Note:
Acquiring and releasing an uncontended Mutex
takes a few microseconds — about 50 times slower than a lock
.
With a Mutex
class, you call the WaitOne
method to lock and ReleaseMutex
to unlock.
Closing or disposing a Mutex
automatically releases it.
Just as with the lock
statement, a Mutex
can be released only from the same thread that obtained it.
A common use for a cross-process Mutex
is to ensure that only one instance of a program can run at a time.
Here’s how it’s done:
class OneAtATimePlease { static void Method() { //Naming a Mutex makes it available computer-wide. //Use a name that's unique to your company and application (e.g., include your URL). using (var mutex = new Mutex(false, "oreilly.com OneAtATimeDemo")) { //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) == false) { Console.WriteLine("Another app instance is running. Bye!"); return; } RunProgram(); } } static void RunProgram() { Console.WriteLine("Running. Press Enter to exit"); Console.ReadLine(); } }
Note:
If running under Terminal Services, a computer-wide Mutex
is ordinarily visible only to applications in the same terminal server session.
To make it visible to all terminal server sessions, prefix its name with Global\.
Mutex Class
A synchronization primitive that can also be used for interprocess synchronization.
Mutex(Boolean, String, Boolean)
Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.
[System.Security.SecurityCritical] public Mutex (bool initiallyOwned, string name, out bool createdNew);
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了