首先lock和Minitor有什么区别呢?
其实lock在IL代码中会被翻译成Monitor。也就是Monitor.Enter(obj)和Monitor.Exit(obj).
lock(obj)
{
}
等价为:
try
{   
      Monitor.Enter(obj)

}
catch()
{}
finally
{
      Monitor.Exit(obj)

}
所以lock能做的,Monitor肯定能做,Monitor能做的,lock不一定能做。那么Monitor额外的功能呢?
1:Monitor.TryEnter(obj,timespan)----timeout之后,就不执行这段代码了。lock可是一直会死等的。

2:还有Monitor.Wait()和Monitor.Pulse()。在lock代码里面如果调用了Monitor.Wait(),会放弃对资源的所有权,让别的线程lock进来。然后别的线程代码里Pulse一下(让原线程进入到等待队列),然后在Wait一下释放资源,这样原线程的就可以继续执行了(代码还堵塞在wait那句话呢)。
也就是说,必须两个或多个线程共同调用Wait和Pulse,把资源的所有权抛来抛去,才不会死锁。

和AutoEvent相似是处理同步关系的,但是AutoEvent是跨进程的,而Monitor是针对线程的。
以下是MSDN的代码示例,调试起来很容易看出来两个函数的作用了,因为尽管是多线程程序,但是是同步操作,所以代码始终是单步执行的。

using System;
using System.Threading;
using System.Collections;

namespace MonitorCS1
{
    class
MonitorSample
    {
       
const int MAX_LOOP_TIME = 100;
       
Queue m_smplQueue;

public MonitorSample()
       
{
           
m_smplQueue = new Queue();
       
}
       
public void FirstThread()
       
{
           
int counter = 0;
           
lock (m_smplQueue)
           
{
               
while (counter < MAX_LOOP_TIME)
               
{
                   
//Wait, if the queue is busy.
                   
Monitor.Wait(m_smplQueue);
                   
//Push one element.
                   
m_smplQueue.Enqueue(counter);
                   
//Release the waiting thread.
                   
Monitor.Pulse(m_smplQueue);

counter++;
               
}
               
int i = 0;
           
}
       
}
       
public void SecondThread()
       
{
           
lock (m_smplQueue)
           
{
               
//Release the waiting thread.
               
Monitor.Pulse(m_smplQueue);
               
//Wait in the loop, while the queue is busy.
               
//Exit on the time-out when the first thread stops.
               
while (Monitor.Wait(m_smplQueue, 50000))
               
{
                   
//Pop the first element.
                   
int counter = (int)m_smplQueue.Dequeue();
                   
//Print the first element.
                   
Console.WriteLine(counter.ToString());
                   
//Release the waiting thread.
                   
Monitor.Pulse(m_smplQueue);
               
}
           
}
       
}
       
//Return the number of queue elements.
       
public int GetQueueCount()
       
{
           
return m_smplQueue.Count;
       
}

static void Main(string[] args)
       
{
           
//Create the MonitorSample object.
           
MonitorSample test = new MonitorSample();
           
//Create the first thread.
           
Thread tFirst = new Thread(new
ThreadStart(test.FirstThread));
           
//Create the second thread.
           
Thread tSecond = new Thread(new
ThreadStart(test.SecondThread));
           
//Start threads.
           
tFirst.Start();
           
tSecond.Start();
           
//wait to the end of the two threads
           
tFirst.Join();
           
tSecond.Join();
           
//Print the number of queue elements.
           
Console.WriteLine("Queue Count = " +
test.GetQueueCount().ToString());
       
}
    }
}

c#中Monitor的使用的更多相关文章

  1. C#中Monitor对象与Lock关键字的区别分析

    这篇文章主要介绍了C#中Monitor对象与Lock关键字的区别,需要的朋友可以参考下 Monitor对象 1.Monitor.Enter(object)方法是获取 锁,Monitor.Exit(ob ...

  2. C#知识点总结系列:4、C#中Monitor和Lock以及区别

    Monitor对象 1.Monitor.Enter(object)方法是获取锁,Monitor.Exit(object)方法是释放锁,这就是Monitor最常用的两个方法,当然在使用过程中为了避免获取 ...

  3. C#中Monitor类、Lock关键字和Mutex类

    线程:线程是进程的独立执行单元,每一个进程都有一个主线程,除了主线程可以包含其他的线程.多线程的意义:多线程有助于改善程序的总体响应性,提高CPU的效率.多线程的应用程序域是相当不稳定的,因为多个线程 ...

  4. C#中Monitor和Lock以及区别

    Monitor对象 1.Monitor.Enter(object)方法是获取锁,Monitor.Exit(object)方法是释放锁,这就是Monitor最常用的两个方法,当然在使用过程中为了避免获取 ...

  5. 锁、C#中Monitor和Lock以及区别

    1.Monitor.Enter(object)方法是获取锁,Monitor.Exit(object)方法是释放锁,这就是Monitor最常用的两个方法,当然在使用过程中为了避免获取锁之后因为异常,致锁 ...

  6. 转:C#中Monitor对象与Lock关键字的区别分析

    Monitor对象1.Monitor.Enter(object)方法是获取 锁,Monitor.Exit(object)方法是释放锁,这就是Monitor最常用的两个方法,当然在使用过程中为了避免获取 ...

  7. 关于android sdk中monitor.exe报错的问题

    今天又是被坑的一上午.来总结一下: 1. 首先是找不到monitor的问题: 这个可能是一开始环境配置错误.所以我将android sdk重装了一下就好了 2. 第二个是找到monitor.bat发现 ...

  8. 【C#】【Thread】Monitor和Lock

    所谓锁,就是之锁定的区域只能单个线程进入进行操作,其他线程在锁的外围等待.Monitor锁通过Monitor.Enter(obj)和Monitor.Exit(obj)来锁定和解锁.Lock锁则直接Lo ...

  9. linux中set的用法

    功能说明:设置shell.语 法:set [+-abCdefhHklmnpPtuvx]补充说明:用set 命令可以设置各种shell选项或者列 出shell变量.单个选项设置常用的特性.在某些选项之后 ...

随机推荐

  1. 【转】linux之shfit

    位置参数可以用shift命令左移.比如shift 3表示原来的$4现在变成$1,原来的$5现在变成$2等等,原来的$1.$2.$3丢弃,$0不移动.不带参数的shift命令相当于shift 1. 非常 ...

  2. 汕头市队赛 SRM10 dp只会看规律 && bzoj1766

    dp只会看规律 SRM 10 描述 平面上有n个点(xi,yi),用最少个数的底边在x轴上且面积为S的矩形覆盖这些点(在边界上也算覆盖) 输入格式 第一行两个整数n,S接下来n行每行两个整数xi,yi ...

  3. 分享C#识别图片上的数字

    通过Emgu实现对图片上的数字进行识别.前期步骤:1.下载Emgu安装文件,我的版本是2.4.2.1777.3.0版本则实现对中文的支持.2.安装后需填写环境变量,环境变量Path值后加入Emgu安装 ...

  4. 【原创】Javascript-获取URL请求参数

    function getUrlParam() { var param = [], hash; var url = window.location.href;//获取网页的url var hashes ...

  5. Codeforces Gym101473 F.Triangles-前缀和 (2013-2014 ACM-ICPC Brazil Subregional Programming Contest)

    前缀和. 代码: 1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include< ...

  6. python-re之中文匹配

    #coding=utf-8 import re import chardet#检测网页编码形式的模块 p = re.compile(r'\d+') print p.findall('one1two2t ...

  7. KMP算法之我见

    预备谈谈下面这些,可能有补充 KMP算法的用途: KMP算法之前的暴力: KMP算法预备知识与概念: KMP算法模板: KMP算法的习题. 1.KMP算法的用途: 主要用于模式匹配(字符串匹配).给定 ...

  8. [Python Debug] SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.

    I Got a SettingWithCopyWarning when I ran the following code: tmp=date[date['date'].isnull().values= ...

  9. Hdoj 2509 Be the Winner

    Diciption Let's consider m apples divided into n groups. Each group contains no more than 100 apples ...

  10. 开始docker

    安装   docker 目前只支持64位系统 1.下载并安装,简直太方便了 $ curl -fsSL https://get.docker.com/ | sh 用例   .docker run hel ...