c# - 跨线程操作在后台工作者 c# 中无效
问题描述
我想要一个在后台工作人员中运行的代码,但遇到了这个错误:
'跨线程操作无效:控件'metroComboBox1'从创建它的线程以外的线程访问。
private void metroRename_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
backgroundWorker1.CancelAsync();
backgroundWorker1.RunWorkerAsync(metroComboBox1.Text);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.Invoke((MethodInvoker)delegate ()
{
string text = metroComboBox1.Text;
});
if (metroComboBox1.SelectedItem == "TITLE") //error here
{
//some code here
}
}
如何在后台工作人员中使用组合框?
解决方案
您也应该将您的条件置于待命状态Invoke
,例如
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.Invoke((MethodInvoker)delegate()
{
string text = metroComboBox1.Text;
if (metroComboBox1.SelectedItem == "TITLE")
{
//some code here
}
});
}
这是有关此问题的现有线程
推荐阅读
- amazon-web-services - 如何在客户端应用程序中订阅 AWS Event Bus 事件
- json - 在不知道键的情况下打印第一个值
- nginx - 无法将流量发送到 nginx 中的 3015 端口
- javascript - 如何从 chome.storage 向列表中添加元素?
- python - Matplotlib 没有绘制所有数据点
- postgresql - 无法使用密码连接到 docker postgres
- c - 达到特定字符串
- sql-server - 通过删除周六和周日生成指标
- python-3.x - 装饰器参数迷失在自我中
- javascript - res.send() 没有发回完整的数据集