调用线程无法访问此对象,因为其他线程拥有它“异常
本文关键字:线程 拥有 其他 异常 因为 对象 访问 调用 | 更新日期: 2023-09-27 18:30:40
嗨,我第一次在线程上工作,不确定我是否做对我收到错误说:
调用线程无法访问此对象,因为其他线程拥有它"异常
private void ImportProductStatsButtonClick(object sender, EventArgs e)
{
// Get the currently selected manufacturer from the combo box
var selected = comboBoxCorporation.SelectedItem;
buttonProductStatsAndRetailerStats.Enabled = false;
buttonSummariseRetailerStats.Enabled = false;
buttonSummariseProductStats.Enabled = false;
// Do we have one?
if (selected != null)
{
// Extract the combo record
var corporation = (ComboBoxCorporrationItem)selected;
// Do we have one?
if (corporation.Corporation != null)
{
// yes
// Make this on a seperate thread so that the UI continues to work
var thread = new Thread(MigrateProductStats);
thread.Start(corporation.Corporation.Id); // This enables me to pick the manufacturer that we are summarizing for
}
}
}
private void MigrateProductStats(object corporationIdObj)
{
// after thread completion I need to Enable my buttons.
buttonProductStatsAndRetailerStats.Enabled = true;
buttonSummariseProductStats.Enabled = true;
}
尝试:
private void MigrateProductStats(object corporationIdObj)
{
Invoke(new Action(() =>
{
// after thread completion I need to Enable my buttons.
buttonProductStatsAndRetailerStats.Enabled = true;
buttonSummariseProductStats.Enabled = true;
});
}
比Control.Invoke
更好的是使用 BackgroundWorker
为您处理线程。 它会在 UI 线程上生成进度和完成事件,以使 UI 更新变得容易。
如果使用的是 C# 5,还可以使用 async
启动后台处理,await
在处理完成后进行 UI 更新。