C#中的BackgroundWorker控件+Delegate.Invoke (委托同步调用)

时间:2022-02-10 22:06:08

C#中的BackgroundWorker控件+Delegate.Invoke (委托同步调用)

简单代码,记录一下。一个BackgroundWorker控件  backgroundWorkerRefresh +listview控件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading; namespace CallCenter
{
public partial class MainFrm : Form
{
public bool isStart = false;
public MainFrm()
{
InitializeComponent();
RefreshDisp();
}
private void RefreshDisp()
{
lv.Items.Clear(); for (int i = ; i < ; i++)
{
ListViewItem lvitem = new ListViewItem();
lvitem.SubItems[].Text = i.ToString();
lvitem.SubItems.Add("项目编号" + i.ToString());
lvitem.SubItems.Add("项目名称" + i.ToString());
lvitem.SubItems.Add("项目负责人" + i.ToString());
lvitem.SubItems.Add("项目年度-" + i.ToString());
lvitem.SubItems.Add(DateTime.Now.ToString() + " -" + i.ToString());
lvitem.SubItems.Add(" #" + i.ToString());
lv.Items.Add(lvitem);
} }
private void RefreshDispCH(int ch)
{ L_Status.Text = lv.Items[ch].SubItems[].Text;
lv.Items[ch].SubItems[].Text = "test";
for (int i = ; i < ; i++)
{
lv.Items[ch].SubItems[i].Text = DateTime.Now.ToString() + " -" + i.ToString();
} } public delegate void D_RefreshDisp();
public delegate void D_RefreshDispCH(int ch); private void backgroundWorkerRefresh_DoWork(object sender, DoWorkEventArgs e)
{
do
{
// this.Invoke(new D_RefreshDisp(RefreshDisp)); Thread.Sleep();
this.Invoke(new D_RefreshDispCH(RefreshDispCH), );
} while (isStart); } private void backgroundWorkerRefresh_ProgressChanged(object sender, ProgressChangedEventArgs e)
{ } private void Startbutton_Click(object sender, EventArgs e)
{
Startbutton.Enabled = false;
isStart = true;
backgroundWorkerRefresh.RunWorkerAsync(); }
}
}