VS2008
.Net3.5
C# WinForm界面上,只有一个button和一个textBox
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Collections;namespace CSharp多线程传参
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Form.CheckForIllegalCrossThreadCalls = false;
} private ArrayList arr = new ArrayList(); private void button1_Click(object sender, EventArgs e)
{
arr.Add(1);
Thread newT1 = new Thread(this.SetLength);//让arr[0]不断++,间隔是
Thread newT2 = new Thread(this.GetLength);//显示arr[0]的值
newT1.Start();
Thread.Sleep(200);
newT2.Start();
} private void FormMove( Form form )
{
//form.Location.X += 50;
Thread.CurrentThread.Abort();
} private void SetLength()
{
//彻底锁住arr
lock (this.arr)
{
while (true)
{
this.arr[0] = (int)this.arr[0] + 1;
Thread.Sleep(300);
}
}
} private void GetLength( )
{
while( true )
{
Thread.Sleep(50);
lock (this.textBox1)
{
this.textBox1.Text = this.arr[0].ToString();
this.arr[0] = (int)this.arr[0] - 1;
}
}
} }
}1。点按钮,执行button1_Click方法。2。newT1线程先执行,彻底锁定 arr,然后让arr[0]++。3。newT2线程在newT1执行了200毫秒后才执行,显示arr[0]的值,并且让arr[0]--。
按理说,newT1里已经彻底lock了arr,为什么newT2还能显示它的值,甚至能修改?
.Net3.5
C# WinForm界面上,只有一个button和一个textBox
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Collections;namespace CSharp多线程传参
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Form.CheckForIllegalCrossThreadCalls = false;
} private ArrayList arr = new ArrayList(); private void button1_Click(object sender, EventArgs e)
{
arr.Add(1);
Thread newT1 = new Thread(this.SetLength);//让arr[0]不断++,间隔是
Thread newT2 = new Thread(this.GetLength);//显示arr[0]的值
newT1.Start();
Thread.Sleep(200);
newT2.Start();
} private void FormMove( Form form )
{
//form.Location.X += 50;
Thread.CurrentThread.Abort();
} private void SetLength()
{
//彻底锁住arr
lock (this.arr)
{
while (true)
{
this.arr[0] = (int)this.arr[0] + 1;
Thread.Sleep(300);
}
}
} private void GetLength( )
{
while( true )
{
Thread.Sleep(50);
lock (this.textBox1)
{
this.textBox1.Text = this.arr[0].ToString();
this.arr[0] = (int)this.arr[0] - 1;
}
}
} }
}1。点按钮,执行button1_Click方法。2。newT1线程先执行,彻底锁定 arr,然后让arr[0]++。3。newT2线程在newT1执行了200毫秒后才执行,显示arr[0]的值,并且让arr[0]--。
按理说,newT1里已经彻底lock了arr,为什么newT2还能显示它的值,甚至能修改?
* 如果 MyType 可以被公共访问,将出现 lock (typeof (MyType)) 问题。
* 由于进程中使用同一字符串的任何其他代码将共享同一个锁,所以出现 lock(“myLock”) 问题。最佳做法是定义 private 对象来锁定, 或 private static 对象变量来保护所有实例所共有的数据。