获取跨线程操作在C#中无效 [英] Getting Cross-thread operation not valid in C#

查看:133
本文介绍了获取跨线程操作在C#中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

跨线程操作无效:从线程以外的线程访问的控制创建的线程

Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

我正在处理一些代码,我初始化一个对象(在这种情况下是一个表单),然后空闲,直到它或者从某人接收到一条消息,或者直接调用其中一种方法。

I am working on some code where I initialize an object (in this case a form), which then idles until it either receives a message from someone, or one of its methods is invoked directly.

在我的表单中,我有一个列表框(lTester),显示对此表单的所有调用。在运行期间,我收到以下错误:

In my form, I have a listbox (lTester) that shows all calls made to this form. During run-time I get the following error:


跨线程操作无效:
控制'lTester'
线程以外的线程是
创建的。

Cross-thread operation not valid: Control 'lTester' accessed from a thread other than the thread it was created on.

我没有手动启动任何线程,事实上我从来没有和他们一起工作,也不知道C#如何在内部管理UI组件。有没有办法解决这个问题?

I have not started any threads manually, in fact I have never worked with them and don't really know how C# manages the UI components internally. Is there any way to get around this?

推荐答案

如果你想知道你的线程来自哪里,你可以放置一个您知道的方法中的断点(生成错误),打开VS中的线程和堆栈跟踪窗口,看看开始调用的起始点。

If you want to know where your thread is comming from, you can place a break point in the method you know are being called (where the error is generated), open the Threads and Stack Trace windows in VS and see what initiated the call to begin with.

即使代码位于Form类中,调用者仍然指定执行调用的线程。这就是为什么,如Oskar所言,您必须检查是否需要 Invoke 到主线程。有很多关于如何做到这一点的例子,只是Google InvokeRequired 并从那里走。

Even though the code is located in your Form class, the caller still desides which thread the call is executed in. That's why, as Oskar stated, you have to check if you need to Invoke to the main thread. There are tons of examples on how to do this, just Google InvokeRequired and go from there.

让我知道如果你需要一个例子。

Let me know if you need an example.

这篇关于获取跨线程操作在C#中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆