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

拟墨画扇 提交于 2019-12-20 09:53:38

问题


What is the Mutex and semaphore in C#? Where we need to implement?

How can we work with them in multithreading?


回答1:


You should start at 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.

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.




回答2:


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:


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.



来源:https://stackoverflow.com/questions/1553012/what-is-the-mutex-and-semaphore-in-c-where-we-need-to-implement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!