use*_*140 3 c# multithreading winforms
我想从我的后台工作人员访问我的GUI上的列表框中的选择.没有任何其他更改尝试这样做会抛出此错误
Cross-thread Operation Not Valid: Control '_ListBox1' accessed from a thread other than the thread it was created on
Run Code Online (Sandbox Code Playgroud)
我看到避免这种情况的选项是使用Invoke以下语法,但是这个.Net 4(或更高)是否可以接受?
var selectedItems = (IList)this.Invoke(new Func<IList>(() => Listbox1.SelectedItems.Cast<object>().ToList()));
Run Code Online (Sandbox Code Playgroud)
为了更清楚地了解这是我想从我的后台工作者访问列表框项目的方式
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 }
}
}
}
Run Code Online (Sandbox Code Playgroud)
Invoke在Backgroundworker's DoWork事件处理程序中,微软不赞成.您应该考虑使用Backgroundworker's ProgressChanged或RunWorkerCompleted事件.
请参阅MSDN帮助.
请参阅本文的第一个注释:
您必须小心不要操作DoWork事件处理程序中的任何用户界面对象.而是通过ProgressChanged和RunWorkerCompleted事件与用户界面进行通信.
如果您实际发布了更多代码,则可能会给出更全面的答案.
编辑1:更多代码
由于OP更新了他的帖子以包含更多代码,我也做了同样的事情.
private void btn1234_Click()
{
var items = ListBox1.SelectedItems.Cast<string>();
backgroundWorker1.RunWorkerAsync(items);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
var items = (IEnumerable<string>)e.Argument;
//Long Running Process taking place here then we hit this
if (items.Contains("Firefly")) { /* take this course */ }
if (items.Contains("Hellfire")) { /* take this course */ }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
317 次 |
| 最近记录: |