定义了一个DataTable dt,两个Button,一个createDt,启动一个线程createThread ,死循环往dt里写数据。另一个deleteDt,启动别一个线程deleteThread ,手动点击,清空dt。原码如下:
public partial class Form1 : Form
{
DataTable dt;
public Form1()
{
InitializeComponent();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("number_id", typeof(int)) });
}
private void createDt_Click(object sender, EventArgs e)
{
Thread createThread = new Thread(TheaderCreate);
createThread.IsBackground = true;
createThread.Start();
}
void TheaderCreate()
{
int x = 0;
lock (dt)
{
while (true)
{
x++;
DataRow dr = dt.NewRow();
dr[0] = x;
dt.Rows.Add(dr);
Thread.Sleep(100);
}
}
}
private void deleteDt_Click(object sender, EventArgs e)
{
Thread deleteThread = new Thread(ThreadDelete);
deleteThread.IsBackground = true;
deleteThread.Start();
}
void ThreadDelete()
{
dt.Clear();
}
按网上的解释,createThread 线程应该是一直占着dt的,deleteThread 线程获取不了dt的使用权。但是结果是:我点击deleteDt的时候,表被清空了!
求解答一下,谢谢大神!