There are some synchronization primitives in .NET used to achieve thread synchronization

Monitor

c# provides System.Threading.Monitor class which cooperates with an objcet to implement locking. Every object has a sync block inside its data stucture,which used by the Monitor to mark down if it is referenced by one thread .The lock statement in c# is implemented by Monitor,and it uses try...catch..finally block to ensure the lock will be released even exception occurs.

Knowing Monitor uses sync block of a object to implement thread locking is helpful to understand the behavior of the lock statement.The figure below describes what happens when using lock statement.

Mutex

The System.Threading.Mutex class derives from System.Threading.WaitHandle class,so Threads request a mutex by calling its WaitOne method, and it provides some overloads to WaitOne method supporting the timeout of waitting.In addition,you can also use the WaitAll,WaitAny or SignalAndWait methods

SpinLock

C# provides a System.Threading.SpinLock class to implement the spin locking. Spin Lock means it will let the thread keep running in loop until it has the access permission to the resource.In most time,OS uses kernel wait handle to block the thread if use synchronous primitives which derives from WaitHandle,like semaphore and WaitEvent class, that means the execution will go through from the managed code and native kernel method, this will bring a performance issue.However, if the lock is held for a very short time,then let the thread run in loop will have a better performance.Of course, keep the thread running can cause a thread context switch and an occupation to CPU, so think twise before using it.

Semaphore

The System.Threading.Semaphore derives from WaitHandle,so can use WaitOne method or WaitAny,WaitAll static method just like Mutex class ,and it allows a specified number of threads to access a resourceIn addional, you can specify a name to a semaphore, a semaphore won't block another thread which has a semaphore of a different name.check the codes below:

    public class SyncSample
{
public void DoWork()
{
Semaphore s = new Semaphore(, , "name_of_semaphore");
s.WaitOne();
Console.WriteLine("doing work");
Thread.Sleep();
Console.WriteLine("work done");
s.Release();
}
}
class Program
{
static void Main(string[] args)
{
SyncSample sc = new SyncSample();
Task.Run(() => { sc.DoWork(); });
Task.Run(() => { sc.DoWork(); });
Console.Read();
}
}

The result is:

If we specify another name, no thread will be blocked:

    public class SyncSample
{
public void DoWork()
{
Semaphore s = new Semaphore(, , Guid.NewGuid().ToString());//will get a different name here
s.WaitOne();
Console.WriteLine("doing work");
Thread.Sleep();
Console.WriteLine("work done");
s.Release();
}
}
class Program
{
static void Main(string[] args)
{
SyncSample sc = new SyncSample();
Task.Run(() => { sc.DoWork(); });
Task.Run(() => { sc.DoWork(); });
Console.Read();
}
}

The result is:

EventWaitHandle

[MSDN]System.Threading.EventWaitHandle class threads to communicate with each other by signaling.Typically,one or more threads block on an EventWaitHandle until an unblocked thread calls the Set method,releasing one or more of the blocked threads.A thread can signal an EventWaitHandle and then block on it,by calling the static WaitHandle.SignalAndWait method.

The constructor accepts an initialState parameter,indicating the initial state of the EventWaitHandler:true then signaled and false is nonsignaled.

The other parameter you can pass into the constructor is EventResetMode enum,being used to controll the behavior of the EventWaitHandle to be AutoReset or ManualRest.AutoRest means the EventWaitHandler is just like a fitting room that has a signal light indicating if it is available or not.When a person gets into the room, the signal light will be off automatically, when the person gets out,the signal light will be turned on automatically ,waitting another person to get in.  On the other hand,ManualRest means the EventWaitHandle is like a gate of the zoo, if the admin open the gate ,ALL waitting people rush into the zoo, until the admin close the gate again, then others people who not yet get into the zoo have to wait for the gate open again.

See also:

WaitHandle Class

Overview of Synchronization Primitives

AutoResetEvent Class

ManualResetEvent Class

Thread in depth 4:Synchronous primitives的更多相关文章

  1. Thread in depth 3:Synchronization

    Synchronization means multi threads access the same resource (data, variable ,etc) should not cause ...

  2. Thread in depth 2:Asynchronization and Task

    When we want to do a work asynchronously, creating a new thread is a good way. .NET provides two oth ...

  3. Thread in depth 1: The basic

    Every single thread has the follow elements: Execution Context:Every thread has a execution context ...

  4. redis-4.0.8 配置文件解读

    # Redis configuration file example.## Note that in order to read the configuration file, Redis must ...

  5. docker+redis安装与配置,主从+哨兵模式

    docker+redis安装与配置 docker安装redis并且使用redis挂载的配置启动 1.拉取镜像 docker pull redis:3.2 2.准备准备挂载的目录和配置文件 首先在/do ...

  6. 009-docker-安装-redis:5.0.3

    1.搜索镜像 docker search redis 2.拉取合适镜像 docker pull redis:5.0.3 docker images 3.使用镜像 docker run -p 6379: ...

  7. 16、Redis手动创建集群

    写在前面的话:读书破万卷,编码如有神 --------------------------------------------------------------------------------- ...

  8. 14、Redis的复制

    写在前面的话:读书破万卷,编码如有神 --------------------------------------------------------------------------------- ...

  9. redis sentinels哨兵集群环境配置

    # Redis configuration file example. # # Note that in order to read the configuration file, Redis mus ...

随机推荐

  1. EasyUI 列表展示及基本格式

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  2. 利用简单的参数传递来实现单条查询的easyui-datagrid

    前一阵子老师给出了一个题目, 说让设计个表格, 学生系统的, 可以查询学生的信息和成绩, 科目自己定, 数据库建表也自己定. 数据库的建表可是建的相当的简陋, 反正老师不是很满意, 后来数据表格做出来 ...

  3. jquery 使用方法(转载)

    原文地址:http://www.cnblogs.com/Chenfengtao/archive/2012/01/12/2320490.html jQuery是目前使用最广泛的javascript函数库 ...

  4. Dubbo简单理解

    Dubbo 致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案.简单的说,Dubbo就是个服务框架,如果没有分布式的需求,其实是不需要用的,只有在分布式的时候,才有Dubbo这样 ...

  5. Codeforces Round #535 (Div. 3)

    E: 题意: 给出n个整数ai和m个区间[li,ri] 你可以选择一些区间,并且将区间内的数字都减一.你要选择一些区间,然后使得改变后的数列中maxbi-minbi的值最大. 题解: 假设我们已经知道 ...

  6. python OSError: [Errno 22] Invalid argument: 'D:\\crawle\x01.html1'

    import urllib.request file = urllib.request.open("http://www.baidu.com") data = file.read( ...

  7. TOYS(叉积)

    TOYS http://poj.org/problem?id=2318 Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 193 ...

  8. ViewPager欢迎界面

    一.几张图片组成欢迎界面 下方有几个点对应每个图片 当图片被选中时对应的点会变亮,当对应的点被点击时也会切换到指定画面 以下是代码 package com.example.viewpager_1; i ...

  9. Spring框架中Bean管理的常用注解

    1. @Component:组件.(作用在类上)可以作用在任何一个类上 2. Spring中提供@Component的三个衍生注解:(功能目前来讲是一致的) * @Controller -- 作用在W ...

  10. Asia Stock Exchanges[z]

    Asia Stock Exchanges July 7, 2009 This article is to summarise the trading rules of some Asia stocke ...