【发布时间】:2015-04-27 18:41:51
【问题描述】:
我想从我的后台工作人员访问我的 GUI 上的列表框中的选择。如果没有任何其他更改尝试这样做会引发此错误
Cross-thread Operation Not Valid: Control '_ListBox1' accessed from a thread other than the thread it was created on
我看到的避免这种情况的选项是通过以下语法使用Invoke,但这是否可以接受.Net 4(或更高版本)?
var selectedItems = (IList)this.Invoke(new Func<IList>(() => Listbox1.SelectedItems.Cast<object>().ToList()));
为了更清晰的图片,这就是我想从我的后台工作人员访问列表框项目的方式
namespace clown
{
public partial class Form1 : Form1
{
public Form1()
{
ListBox1.Items.Add("Firefly");
ListBox1.Items.Add("Hellfire");
}
private void btn1234_Click()
{
backgroundworker1.RunWorkerAsync();
}
private void backgroundworker1_DoWork(object sender, DoWorkEventArgs e)
{
//Long Running Process taking place here
//then we hit this
if (ListBox1.SelectedItems.Contains("Firefly")) { //take this course }
if (ListBox1.SelectedItems.Contains("Hellfire)) { //take this course }
}
}
}
【问题讨论】:
-
.Net 4 可接受是什么意思?是指明智的标准还是明智的编译?
-
你试过了吗?发生了什么?
-
“访问选择”是什么意思?您使用的是什么 API? ASP.NET?表格? WPF? Metro(或本周微软所称的任何东西)?
-
@Alex & Josh L.- 它有效,免费发行。只是不确定这样做是否“可以接受”。
标签: c# multithreading winforms