Monitor类与Lock语句相比,Monitor类的主要优点是:可以添加一个等待被锁定的超时值。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { ShareClass sc = new ShareClass(); Job j=new Job (sc); Task[] ts=new Task[20]; for (int i = 0; i < 20; i++) { ts[i] = new Task(j.TheDoJob2); ts[i].Start(); } for (int i = 0; i < 20; i++) { ts[i].Wait(); } Console.WriteLine(sc.state); Console.ReadKey(); } } class ShareClass { public int state { get; set; } } class Job { ShareClass sc { get; set; } private object obj = new object(); public Job(ShareClass s) { sc = s; } //==========普通的Monitor类 public void TheDoJob() { //锁定 Monitor.Enter(obj); try { for (int i = 0; i < 10000; i++) { sc.state++; } } catch { } finally { //如果抛出异常也会就出锁 //释放锁 Monitor.Exit(obj); } } //===========给Monitor类设置超时时间 public void TheDoJob2() { bool yesno=false; //锁定 Monitor.TryEnter(obj, 100, ref yesno); if (yesno) { for (int i = 0; i < 10000; i++) { sc.state++; } Console.WriteLine("yes"); //释放锁 Monitor.Exit(obj); } else { //如果超时会执行下面代码 Console.WriteLine("no"); } } } }
TheDoJob()
TheDoJob2()
时间: 2024-11-02 23:34:09