跨线程操作无效:尝试从列表框删除项目时 [英] Cross-thread operation not valid: while tried to remove item from Listbox
问题描述
跨线程操作无效:控制listbox1从与其在其上创建的线程不同的线程访问
我在ListBox中有代表ADD项目的委托.在添加新项目之前,我检查它是否已在列表中.如果是,则从列表中删除并添加新项目.
当我尝试删除旧项目时,它给出了错误.
跨线程操作无效:从不在其上创建线程的线程访问控件listbox1"
我不能在一次通话中同时进行这两项操作吗?
请帮我!!! :(
谢谢
Seema
Cross-thread operation not valid: Control listbox1 accessed from a thread other than the thread it was created on
I have delegate for ADD items in ListBox. Before add new item I check is it already in the list If yes then Remove from the List and add new one.
As I tried to remove old item It gives error.
"Cross-thread operation not valid: Control listbox1 accessed from a thread other than the thread it was created on"
Can''t I do both operation together in single call??
Please help me!!! :(
Thank you
Seema
推荐答案
您应该只从创建UI元素的线程中访问UI元素
如何:对Windows窗体控件进行线程安全调用 [ ^ ]
使用列表框的"InvokeRequired"属性来查看是否需要编组回UI线程
例如
You should only access UI elements from the thread that created them
How to: Make Thread-Safe Calls to Windows Forms Controls [^]
Use the ''InvokeRequired'' property of your listbox to see if you need to marshal back to the UI thread
e.g.
private void LoadItems()
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.listbox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
// Load your items here
}
}
另外,如果您使用的是.Net 4.0,则可能需要查看任务并行库 [ ^ ],您可以使用使用延续并传递自动编组回UI的同步上下文
http://blogs. msdn.com/b/csharpfaq/archive/2010/06/18/parallel-programming-task-schedulers-and-synchronization-context.aspx [
Alternatively, if you''re using .Net 4.0, you might want to look at the Task Parallel Library[^] which allows you to use continuations and pass a Synchronization Context that automatically marshalls back to the UI
http://blogs.msdn.com/b/csharpfaq/archive/2010/06/18/parallel-programming-task-schedulers-and-synchronization-context.aspx[^]
Just noticed the .Net 3.5 tag! I''ll leave the TPL reference in my answer though, might help someone else
别忘了Google,您甚至在发布问题之前尝试在CP上找到答案.
我进行了google搜索,第一个结果是此 [
Leave alone Google, did you even try to find answer on CP before posting the question.
I did the google search and the first result was for this [^]on Code Project.
It explains it nicely.
这篇关于跨线程操作无效:尝试从列表框删除项目时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!