读书人

C# 关于Monitor解决思路

发布时间: 2012-08-14 10:39:58 作者: rapoo

C# 关于Monitor

C# code
 public partial class Form1 : Form    {        private ThreadStart myStart;        private ParameterizedThreadStart myPStart;        int m, n, t;        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            myStart = new ThreadStart(ShowNamea);            Thread thA = new Thread(myStart);            myPStart = new ParameterizedThreadStart(ShowNameObj);            Thread thB = new Thread(myPStart);            thA.Start();            thB.Start(2);                    }        private void ShowNamea()        {            while(true)            {                Thread.Sleep(100);                try                {                    Monitor.Enter(t);                    if (t % 2 != 0)                    {                        Monitor.Wait(t);                    }                    t += 2;                    Monitor.Pulse(t);                }                finally                {                    Monitor.Exit(t);                } m++;            }        }        private void ShowNameObj(object obj)        {            int num = (int)obj;            while (true)            {                Thread.Sleep(100);                try                {                    Monitor.Enter(t);                    if (t % 2 != num)                    {                        Monitor.Wait(t);                    }                    t += num;                    Monitor.Pulse(t);                }                finally                {                    Monitor.Exit(t);                }                n++;            }        }}


运行会报“从不同步的代码块中调用了对象同步方法”的异常,求解惑。

[解决办法]
只能Monitor引用类型,不能是值类型
[解决办法]
探讨

引用:
只能Monitor引用类型,不能是值类型

C# code

public partial class Form1 : Form
{
private ThreadStart myStart;
private ParameterizedThreadStart myPStart;
int m, n, s =……

[解决办法]
int装箱导致,不同代码段锁的对象是不一样的,在同一个代码段中,进入和释放的对象也是不一样的。另外我看到还有Monitor.Pulse,它的用法最好看一下这篇经典文章http://topic.csdn.net/u/20111209/18/2fa51d2e-ba01-4c28-a7d2-2719e6de3c8f.html

读书人网 >C#

热点推荐