如何解决C#.NET中的跨线程问题? [英] How to resolve the cross thread issue in C#.NET?

查看:64
本文介绍了如何解决C#.NET中的跨线程问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在为64位系统迁移32 C#.net Windows应用程序,而在我的应用程序中,我正在使用MODI来对映像进行OCR能够迁移应用程序,但问题是每当我运行应用程序时它都会给我一个错误



从线程以外的线程访问控制'axMiDocView1'它创建于。



这是我遇到此错误的代码行:





Hi,

I'm migrating a 32 C#.net windows application for 64 bit system and in my application I'm using MODI for OCRing an image I'm able to migrate the application but the problem is whenever i run the application it gives me an error

"Control 'axMiDocView1' accessed from a thread other than the thread it was created on."

Here's the code Lines where I'm getting this error:


this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.axMiDocView1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();





无论什么时候到来to this.performlayout它抛出异常。





任何帮助表示赞赏:



提前致谢



Whenever it comes to this.performlayout it throws the exception.


Any Help is appreciated:

Thanks in advance

推荐答案

这是一个非常常见的问题:某些类型或某些设施的实例只能在一个线程中运行。这种限制是为了简化他们的代码。你需要遵循这个设计并通过同一个线程执行所有相应的代码部分。



这并不意味着你不能使用多个线程。如果需要线程之间的协作,则需要使用线程同步和线程间通信。特别是,有一种调用机制可以将一些操作从一个线程委托给一个UI线程。请查看我过去的答案:

Control.Invoke( )与Control.BeginInvoke() [ ^ ],

Treeview扫描仪和MD5的问题 [ ^ ]。



如果你想开发一些非UI线程来调用其他线程的委托,您将需要使用循环并创建一些类似的机制。请参阅:

http:// msdn .microsoft.com / zh-CN / library / dd267312%28v = vs.110%29.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/dd997371%28v=vs.110%29.aspx [ ^ ]。



在我的文章中,我解释了这些工作如何工作,而不使用 BlockingCollection

用于线程通信和Inter-的简单阻塞队列线程调用 [ ^ ]。



-SA
This is a very usual issue: instances of certain types or certain facilities can only work in one single thread. This limitation is done to simplify their code. You need to follow this design and execute all corresponding parts of code by the same thread.

It does not mean that you cannot use multiple threads. If you need collaboration between thread, you will need to use thread synchronization and inter-thread communication. In particular, there is an invocation mechanism to delegate some action from one thread to a UI thread. Please see my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

If you want to develop some non-UI thread to invoke delegates from other thread, you will need to use a loop and create some analogous mechanism. Please see:
http://msdn.microsoft.com/en-us/library/dd267312%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/dd997371%28v=vs.110%29.aspx[^].

In my article, I explained how such things work, without using BlockingCollection:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].

—SA


这篇关于如何解决C#.NET中的跨线程问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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