我有一个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;
}
}