多线程【C#】

【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,
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值