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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:46:16  来源:igfitidea点击:

What is the Mutex and semaphore In c#? where we need to implement?

c#multithreadingmutexsemaphore

提问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 开始。

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 链接支持它。