System.Threading.Mutex: A synchronization primitive that can also be used for interprocess synchronization.
System.Threading.Semaphore: Limits the number of threads that can access a resource or pool of resources concurrently.
Generally you only use a Mutex across processes, e.g. if you have a resource that multiple applications must share, or if you want to build a single-instanced app (i.e. only allow 1 copy to be running at one time).
A semaphore allows you to limit access to a specific number of simultaneous threads, so that you could have, for example, a maximum of two threads executing a specific code path at a time.
class Test {
private static object Lock = new object();
public function Synchronized()
{
lock(Lock)
{
// Only one thread at a time is able to enter this section
}
}
}
语句是通过调用Monitor.Enter和Monitor.Exit来实现的。它相当于下面的代码:
Monitor.Enter(Lock);
try
{
// Only one thread at a time is able to enter this section
}
finally
{
Monitor.Exit(Lock);
}
You might want to check out the lock statement. It can handle the vast majority of thread synchonization tasks in C#
class Test {
private static object Lock = new object();
public function Synchronized()
{
lock(Lock)
{
// Only one thread at a time is able to enter this section
}
}
}
The lock statement is implemented by calling Monitor.Enter and Monitor.Exit. It is equivalent to the following code:
Monitor.Enter(Lock);
try
{
// Only one thread at a time is able to enter this section
}
finally
{
Monitor.Exit(Lock);
}
发布评论
评论(3)
您应该从 MSDN 开始。
通常,您仅跨进程使用互斥锁,例如,如果您拥有多个应用程序必须共享的资源,或者您想要构建单实例应用程序(即一次只允许运行 1 个副本)。
信号量允许您限制对特定数量的并发线程的访问,这样您就可以同时最多有两个线程执行特定的代码路径。
You should start at MSDN.
Generally you only use a Mutex across processes, e.g. if you have a resource that multiple applications must share, or if you want to build a single-instanced app (i.e. only allow 1 copy to be running at one time).
A semaphore allows you to limit access to a specific number of simultaneous threads, so that you could have, for example, a maximum of two threads executing a specific code path at a time.
我首先阅读以下内容: http://www.albahari.com/threading/part2 .aspx#_Synchronization_Essentials
然后使用 bobbymcr 发布的 MSDN 链接来支持它。
I'd start by reading this: http://www.albahari.com/threading/part2.aspx#_Synchronization_Essentials
and then bolster it with the MSDN links bobbymcr posted.
您可能想检查锁定语句。它可以处理C#中绝大多数线程同步任务。lock
语句是通过调用Monitor.Enter和Monitor.Exit来实现的。它相当于下面的代码:
You might want to check out the lock statement. It can handle the vast majority of thread synchonization tasks in C#
The lock statement is implemented by calling Monitor.Enter and Monitor.Exit. It is equivalent to the following code: