C#利用线程查询数据库数据,出现假死现象
当数据库里数据量大的时候,查询会出现假死现象,代码如下,请各高人指导:
public partial class Form6 : Form
{
public delegate void myDelegate();
DataTable dt;
Thread tSo;
private MMS.Public.DbAccLibry.DbAccess mydbacc;
public Form6()
{
mydbacc = new MMS.Public.DbAccLibry.DbAccess();
mydbacc.DatabaseInint(MMS.Public.DbAccLibry.DataBaseType.MsSqlServer, "Server=192.192.192.8;Database=escashsystem;User ID=sa;Password=Hy@ecSun.cn;Connect Timeout=20;Pooling=True;Min Pool Size=1;Max Pool Size=100;Persist Security Info=False;Asynchronous Processing=true;Integrated Security=false;");
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
tSo = new Thread(new ThreadStart(ThreadWork));
tSo.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString() + ",数据查询失败", "查询提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
void ThreadWork()
{
label2.BeginInvoke(new myDelegate (aa)) ;
this.dataGridView1.BeginInvoke(new myDelegate(FillData));//异步调用(来填充)
//this.Cursor = Cursors.Default;
label2.BeginInvoke(new myDelegate(bb));
}
private void FillData()
{
dt = mydbacc.ExecuteDataSet(CommandType.Text, "select * from ecv_spbaseinfo ").Tables[0];
this.dataGridView1.DataSource = dt.DefaultView;
}
private void aa()
{
this.label2.Text = "正在查询电价数据...";
}
private void bb()
{
this.label2.Text = "查询结束...";
}
}
------解决方案--------------------
建议改为:
public delegate void PDelegate(DataTable t);
void ThreadWork()
{
label2.BeginInvoke(new myDelegate (aa)) ;
DataTable dt = mydbacc.ExecuteDataSet(CommandType.Text, "select * from ecv_spbaseinfo ").Tables[0];
this.dataGridView1.BeginInvoke(new PDelegate(FillData),new object[]{dt});//异步调用(来填充)
//this.Cursor = Cursors.Default;
label2.BeginInvoke(new myDelegate(bb));
}
private void FillData(DataTable dt)
{
this.dataGridView1.DataSource = dt.DefaultView;
}