【C#动态加载数据】“防界面卡死”

时间:2024-03-16 13:24:38
using System; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; // 引入SqlClient命名空间以使用ADO.NET public partial class YourForm : Form { private BackgroundWorker backgroundWorker; public YourForm() { InitializeComponent(); backgroundWorker = new BackgroundWorker(); backgroundWorker.WorkerReportsProgress = true; // 如果你不需要报告进度,可以设置为false backgroundWorker.DoWork += BackgroundWorker_DoWork; //task开始执行方法 backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(DW_Change_Progress);//进度汇报事件 backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted; //task结束事件 } private void StartButton_Click(object sender, EventArgs e) { List<string> param= new List<string>(){"back_work_intput_parameter"}; if (!backgroundWorker.IsBusy) { // 在开始工作之前,可以禁用UI元素以防止用户进行其他操作 StartButton.Enabled = false; backgroundWorker.RunWorkerAsync(param); // 启动后台工作 } } private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { List<string> param = (List<string>)e.Argument;//获取入参 if (param.Count < 1) return; // 这个方法将在后台线程上执行 try { using (SqlConnection connection = new SqlConnection(YourConnectionString)) // 替换为你的连接字符串 { connection.Open(); using (SqlCommand command = new SqlCommand("SELECT * FROM YourTable", connection)) // 替换为你的SQL查询和表名 { using (SqlDataReader reader = command.ExecuteReader()) { DataTable dataTable = new DataTable(); dataTable.Load(reader); // 将DataTable作为结果传递给RunWorkerCompleted事件处理程序 e.Result = dataTable; } } } } catch (Exception ex) { // 将异常传递给RunWorkerCompleted事件处理程序 e.Result = ex; } } public void DW_Change_Progress(object sender, ProgressChangedEventArgs e) { Progress.Value = (float)e.ProgressPercentage / (float)db_name_list.Count; } private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // 这个方法将在UI线程上执行,当DoWork完成时 if (e.Error != null) { // 处理异常 MessageBox.Show(e.Error.Message); } else { // 获取并处理数据 DataTable dataTable = e.Result as DataTable; if (dataTable != null) { // 更新UI,例如将数据绑定到DataGridView等控件上 yourDataGridView.DataSource = dataTable; } } finally { // 重新启用UI元素 StartButton.Enabled = true; } } }