c# - 全部加载后更新主用户界面
问题描述
问题如下,它执行另一种形式但使用主要形式,因此程序变得“不可用”。
我尝试使用 backgroundworker 但在发现此方法并切换后。
private async void Disp_data_Sim()
{
var windowToOpen = new WaitingWorker()
{
Owner = this,
};
await Task.Run(new Action(() =>
{
this.BeginInvoke((MethodInvoker)delegate
{
windowToOpen.ShowDialog();
});
try
{
var tempCon = File.ReadAllText("DBConnection.json");
var tempCon1 = Crypt.Decrypt(tempCon, "encryption");
var sqlInfo = new JavaScriptSerializer().Deserialize<SQLInfo>(tempCon1);
using (SqlConnection con = new SqlConnection(sqlInfo.GetConString()))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT referencia,descricao,pr_custo1,etiqueta,qtd FROM Etiquetas Where etiqueta = @etiqueta";
cmd.Parameters.AddWithValue("@etiqueta", 'S');
DataTable dtbl = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtbl);
dataGridView1.Invoke(new Action(() => dataGridView1.DataSource = dtbl));
}
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
this.Invoke((MethodInvoker)delegate
{
windowToOpen.Close();
});
}));
}
我想要做的是,我需要在另一个线程中打开另一个表单,其中有一个不确定的进度条,并且在主 ui 中我需要在负载消失后使用 bd 数据更新数据网格。
解决方案
您应该避免混合 UI 和非 UI 代码。
尝试这个:
private async void Disp_data_Sim()
{
var windowToOpen = new WaitingWorker()
{
Owner = this,
};
try
{
windowToOpen.ShowDialog();
dataGridView1.DataSource = await GetDataAsync();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
windowToOpen.Close();
}
private async Task<DataTable> GetDataAsync()
{
var tempCon = File.ReadAllText("DBConnection.json");
var tempCon1 = Crypt.Decrypt(tempCon, "encryption");
var sqlInfo = new JavaScriptSerializer().Deserialize<SQLInfo>(tempCon1);
using (SqlConnection con = new SqlConnection(sqlInfo.GetConString()))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT referencia,descricao,pr_custo1,etiqueta,qtd FROM Etiquetas Where etiqueta = @etiqueta";
cmd.Parameters.AddWithValue("@etiqueta", 'S');
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dtbl = new DataTable();
await con.OpenAsync();
await Task.Yield(); // just to make sure it yields back to the caller.
da.Fill(dtbl);
return dtbl;
}
}
}
}
不幸的是,SqlDataAdapter
它没有异步 API。您可以通过使用 aSqlDataReader
并自己填写表格来改善这一点。
推荐阅读
- wordpress - WooCommerce 不允许我设置自定义订单状态
- c# - Viewbag 是否返回 null?
- python - 如何解决“列表”对象没有“应用”属性
- r - 无法使用 RODBC 附加 teradata 易失性表
- python - 为什么在 CNN 的输出层中使用 softmax 而不是 sigmoid 会得到截然不同的结果?
- python - Python如何在不引用其原始实例的情况下使用另一个实例的属性启动一个新实例?
- javascript - Jasmine 对瞬态属性的单元测试
- python - 接客户订单
- react-native - 此版本的“@react-navigation/native”与 React Navigation 5 不兼容
- alpha-vantage - 如何从 Alpha Vantage 获取实时数据?