c#中的互斥量和信号量是什么?我们需要在哪里实施?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1553012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the Mutex and semaphore In c#? where we need to implement?
提问by Jaswant Agarwal
What is the Mutex and semaphore in C#? Where we need to implement?
C#中的互斥量和信号量是什么?我们需要在哪里实施?
How can we work with them in multithreading?
我们如何在多线程中使用它们?
回答by bobbymcr
You should start at MSDN.
你应该从 MSDN 开始。
- 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.
- System.Threading.Mutex:一个同步原语,也可用于进程间同步。
- System.Threading.Semaphore:限制可以同时访问资源或资源池的线程数。
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).
通常,您只在进程间使用互斥锁,例如,如果您有多个应用程序必须共享的资源,或者您想构建单实例应用程序(即一次只允许运行 1 个副本)。
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.
信号量允许您限制对特定数量的并发线程的访问,例如,这样您最多可以同时有两个线程执行特定的代码路径。
回答by Pete
You might want to check out the lock statement. It can handle the vast majority of thread synchonization tasks in C#
您可能想查看 lock 语句。它可以处理 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:
lock 语句是通过调用 Monitor.Enter 和 Monitor.Exit 实现的。它等效于以下代码:
Monitor.Enter(Lock);
try
{
// Only one thread at a time is able to enter this section
}
finally
{
Monitor.Exit(Lock);
}
回答by Ed Power
I'd start by reading this: http://www.albahari.com/threading/part2.aspx#_Synchronization_Essentialsand then bolster it with the MSDN links bobbymcr posted.
我首先阅读此内容:http: //www.albahari.com/threading/part2.aspx#_Synchronization_Essentials,然后使用 bobbymcr 发布的 MSDN 链接支持它。