在主 UI 线程上更新控件的正确方法是什么
What is the correct way to update controls on main UI thread
在我的 C# winforms 应用程序中,我在后台使用 Task 从数据库加载数据,下面是我的代码。但在上传数据后,我正在更新我的 UI 控件,即 BindingSource。此 BindingSource 组件连接到也将更新的 DataGrid。
我需要知道的是我正在做的是正确的方法还是有其他更好的方法来实现同样的目标。
private async void Form_Load(object sender, EventArgs e)
{
Task loadDataTask = Task.Factory.StartNew(() =>
{
// LoadData(); // loading the data from the database
});
await loadDataTask.ConfigureAwait(true);
FormBindingSource.DataSource = _businessObjecsCollection;
}
如果你负担得起,让加载数据的方法异步。那么您将能够将 Form 方法更改为:
private async void Form_Load(object sender, EventArgs e)
{
await LoadDataAsync();
FormBindingSource.DataSource = _businessObjecsCollection;
}
甚至
private async void Form_Load(object sender, EventArgs e)
{
FormBindingSource.DataSource = await LoadDataAsync();
}
否则目前的方法似乎没问题
在我的 C# winforms 应用程序中,我在后台使用 Task 从数据库加载数据,下面是我的代码。但在上传数据后,我正在更新我的 UI 控件,即 BindingSource。此 BindingSource 组件连接到也将更新的 DataGrid。
我需要知道的是我正在做的是正确的方法还是有其他更好的方法来实现同样的目标。
private async void Form_Load(object sender, EventArgs e)
{
Task loadDataTask = Task.Factory.StartNew(() =>
{
// LoadData(); // loading the data from the database
});
await loadDataTask.ConfigureAwait(true);
FormBindingSource.DataSource = _businessObjecsCollection;
}
如果你负担得起,让加载数据的方法异步。那么您将能够将 Form 方法更改为:
private async void Form_Load(object sender, EventArgs e)
{
await LoadDataAsync();
FormBindingSource.DataSource = _businessObjecsCollection;
}
甚至
private async void Form_Load(object sender, EventArgs e)
{
FormBindingSource.DataSource = await LoadDataAsync();
}
否则目前的方法似乎没问题