【Thread】
Thread thread = new Thread(ThreadStart start);
。。。。。
thread.IsBackground = true;
thread.Start();
public delegate void ThreadStart();
所以,参数的类型是方法。
(
() =>
{
this.txtV.Invoke(new Action<string>(data =>
{
this.lblV.Text = data;//将读取的控件值,在其他控件中显示出来
}), this.txtV.Text);
});
thread.IsBackground = true;
thread.Start();
public object Invoke(Delegate method, params object[] args)//【方法,参数】
子控件都继承 .Invoke
this.dgv1.Invoke(new Action<DataTable>(t => { this.dgv1.DataSource = t; }), dt1);
//访问数据库
private void btnExecute1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(() =>
{
string classCount = DBUtility.SQLHelper.GetSingleResult("select count(*) from Products").ToString();
this.lblResult1.Invoke(new Action<string>(count => { this.lblResult1.Text = count; }), classCount);
});
thread.IsBackground = true;
thread.Start();
}
//跨线程访问数据库,并在dgv中展示数据
private void btnGetData_Click(object sender, EventArgs e)
{
Thread thread = new Thread(() =>
{
DataSet ds = DBUtility.SQLHelper.GetDataSet("select * from ProductInventory;select ProductId,ProductName,Unit from Products");
DataTable dt1 = ds.Tables[0];
DataTable dt2 = ds.Tables[1];
this.dgv1.Invoke(new Action<DataTable>(t => { this.dgv1.DataSource = t; }), dt1);
this.dgv2.Invoke(new Action<DataTable>(t => { this.dgv2.DataSource = t; }), dt2);
});
thread.IsBackground = true;
thread.Start();
}
}
【启动】 .Start();
thread = new Thread(() =>
{
while (true)
{
try
{
Thread.Sleep(500);
lblInfo.Invoke(new Action(() =>
{
lblInfo.Text += counter++ + ",";
}));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " 异常位置:" + counter++);
}
}
});
thread.Start();
【暂停】.Suspend();
//暂停
private void btnSuspend_Click(object sender, EventArgs e)
{
if (thread.ThreadState == ThreadState.Running ||
thread.ThreadState == ThreadState.WaitSleepJoin)
{
thread.Suspend();
}
}
【继续】.Resume();
//继续
private void btnResume_Click(object sender,