当前位置:网站首页>使用多线程写winform程序

使用多线程写winform程序

2022-01-15 02:02:42 罗迪尼亚的熔岩

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SQLThreading
{
    
    public partial class FrmThreadDataBase : Form
    {
    
        public FrmThreadDataBase()
        {
    
            InitializeComponent();
        }

        private void btnExecute1_Click(object sender, EventArgs e)
        {
    
            Thread th1 = new Thread(() =>
            {
    
                Thread.Sleep(2000);
                string classCount = Helper.GetSingleResult("select count(*) from StudentClass").ToString();
                this.lblResult1.Invoke(new Action<string>(t => {
     this.lblResult1.Text = t; }),classCount);
            });
            th1.IsBackground = true;
            th1.Start();
        }

        private void btnExecute2_Click(object sender, EventArgs e)
        {
    
            Thread th2 = new Thread(() =>
            {
    
                Thread.Sleep(2000);
                string stuCount = Helper.GetSingleResult("select count(*) from Students").ToString();
                this.lblResult2.Invoke(new Action<string>(t => {
     this.lblResult2.Text = t; }), stuCount);
            });
            th2.IsBackground = true;
            th2.Start();
        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
    
            Thread th3 = new Thread(() =>
            {
    
                Thread.Sleep(2000);
                //string stuCount = Helper.GetSingleResult("select count(*) from Students").ToString();
                //this.lblResult2.Invoke(new Action<string>(t => { this.lblResult2.Text = t; }), stuCount);

                //访问数据库, 同时访问2个表, 用分号隔开 Select 后面选择的, 是要显示的列名
                //Invoke 可以跨线程使用. Action 无返回值的泛型委托
                //sleep, 延迟, 可以看到过程
                //dgv绑定数据源
                //注意DataSet, DataTable, DataRow, DataColoumn的关系 
                DataSet ds = Helper.GetDataSet("Select * from StudentClass;select StudentName,Gender,PhoneNumber from Students") ;
                DataTable dt1 = ds.Tables[0];
                DataTable dt2 = ds.Tables[1];

                this.dgv1.Invoke(new Action<DataTable>(c =>
                {
    
                    this.dgv1.DataSource = c;
                }),dt1);
                Thread.Sleep(2000);
                this.dgv2.Invoke(new Action<DataTable>(s=>this.dgv2.DataSource=s),dt2);

            });
            th3.IsBackground = true;
            th3.Start();
        }
    }
}

版权声明
本文为[罗迪尼亚的熔岩]所创,转载请带上原文链接,感谢
https://blog.csdn.net/helldoger/article/details/121955590

随机推荐