猿问

Lock怎么锁不住啊?

public partial class Form1 :     {         private static readonly object myLock = new object();         Thread trd;         DataTable dt;         public Form1()         {             InitializeComponent();             dt = new System.Data.DataTable();             DataColumn col = new System.Data.DataColumn();              col.ColumnName = "aa";              dt.Columns.Add(col);         }         private void button1_Click(object sender, EventArgs e)         {              trd = new Thread(delegate()             {                 lock (myLock)                  {                     DataRow drow = dt.NewRow();                      drow["aa"] = "55";                      dt.Rows.Add(drow);                     while (true)                      {                         //一直循环                      }                 }             });               trd.Start();         }           private void button2_Click(object sender, EventArgs e)         {             DataRow drow = dt.NewRow();              drow["aa"] = "66";              dt.Rows.Add(drow);          }   按钮1 开了死循环线程 锁住了啊 怎么按钮2还可以 往 Datatable里加数据呢?
哈士奇WWW
浏览 483回答 5
5回答

繁花不似锦

btn2也加上锁就是了 private void button2_Click(object sender, EventArgs e) { lock(myLock) { DataRow drow = dt.NewRow(); drow["aa"] = "66"; dt.Rows.Add(drow); } }  

幕布斯7119047

你锁住了代码1,和个代码2有啥关系呢????

素胚勾勒不出你

1. 锁的对象是 myLock,又不是 Datatable,当然其它线程能操作 Datatable。2. Datatable 是实例对象,每次操作都是不同的Datatable 对象,你也锁不定它,操作2中的Datatable和操作1中的 Datatable是不同的对象,不搭嘎。

杨魅力

private static readonly object myLock = new object();         改成: Public static readonly object myLock = new object();        
随时随地看视频慕课网APP
我要回答