我有一个datagridview,我需要每秒从数据库刷新一次。我编写了这段代码,以便我的UI不会冻结,数据获取操作在后台运行,但它仍然会冻结/滞后我的UI。我需要你的专业知识让我知道我在这里犯了什么错误。
我有一个主表单,我在这里调用名为Symbols的表单。
Symbols childForm1 = new Symbols();
childForm1.MdiParent = this;
this.SplitContainer2.Panel1.Controls.Add(childForm1);
childForm1.Dock = DockStyle.Fill;
childForm1.Show();
符号形式的代码 - >
public DataSet Result { get { return (DataSet)this.dataGridView1.DataSource; } set { this.dataGridView1.DataSource = value.Tables[0]; } }
private Task<DataSet> StartBackgroundWork()
{
return new WorkItem().DoWork();
}
private void Form_Load(object sender, EventArgs e)
{
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (1000);
MTimer.Tick += MyTimer_Tick;
MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{
this.StartBackgroundWork()
.ContinueWith((t) => this.Result = t.Result, TaskScheduler.FromCurrentSynchronizationContext()); ;
}
public class WorkItem
{
public Task<DataSet> DoWork()
{
return Task.Factory.StartNew<DataSet>(this.PerformWork);
}
private DataSet PerformWork()
{
DataSet dt = new DataSet();
ServiceReference1.tblOrder obj = new ServiceReference1.tblOrder();
obj.order_id = login.client_id;
ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client();
dt = objService.symboldata(obj);
return dt;
}
}
答案 0 :(得分:0)
使用 BackgroundWorker 类来避免冻结ui。