问题描述
我有一个后台工作人员,我试图让它创建表单实例,但是我不希望后台工作人员线程拥有该对象,但是会就像拥有它的主线程一样.我从哪里开始呢?
I've got a background worker and I'm trying to get it to create an instance of a form, but I don't want the background worker thread to own the object, but would like the main thread to own it. Where do I start with this?
推荐答案
您可以使用调用和BeginInvoke函数以获取要在GUI线程上执行的代码.您可以让另一个线程引发一个事件,然后以您的主表单处理该事件,然后您的主表单可以将该调用调回到其自己的线程上(使用InvokeRequired然后是Invoke)以启动新表单.
You can use the Invoke and BeginInvoke functions to get the code to execute on the GUI thread. You could get your other thread to raise an event, then handle it in your main form, then your main form could invoke that call back onto its own thread (using InvokeRequired then Invoke) to launch the new form.
如果您正在使用后台工作者,则可以将OnProgressChanged方法用于通知您的应用程序以执行某些操作.
If you're using a background worker you may be able to put the OnProgressChanged method to use to signal back to your application to do something.
还要看一看这本优秀的书
这篇关于使用backgroundworker在主线程上创建WinForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!