如何在另一个线程启动时停止主线程&在第二个线程停止后恢复主线程 [英] How to stop main thread while another thread starts & resume main thread after the 2nd thread stops

查看:139
本文介绍了如何在另一个线程启动时停止主线程&在第二个线程停止后恢复主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


有人可以告诉我如何在另一个线程想要运行时停止并恢复连续运行的主线程.

我有主线程连续进行设备轮询,因为当我获得一些数据时,将执行一个特定的操作,为此启动另一个线程,但是为此,主线程必须停止并服务子线程.子线程完成后,主线程应继续轮询.那么如何在Windows窗体中实现这样的任务.

在此先谢谢您.

Hi all,


Can anybody tell me how to stop & resume the main thread which is running continuously, when another thread wants to run.

I have main thread which does polling of a device continuously, as & when i get some data, a particular action is to be done for which another thread is initiated but for this the main thread has to stopped & service the child thread. Once the child thread finishes, main thread should continue polling. So how to achieve such task in windows form.

Thanks in Advance.

推荐答案

此方案看起来很复杂,同时又过多.我几乎肯定您的设计还没有被很好的考虑.这是您最好开始的地方.您想直接通过线程同步在线程之间创建依赖关系,这很容易弄乱事情.

您应该考虑的一种重要技术是生产者-消费者设计模式.请参阅: http://en.wikipedia.org/wiki/Producer-consumer_problem [ http://msdn.microsoft.com/en-us/library/dd997371%28v = vs.110%29.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/dd267312%28v = vs.110%29.aspx [ ^ ].

对于.NET BCL的早期版本,甚至是4.0或更高版本,请参阅我的文章,其中实现了这样的阻塞队列,并说明了如何在所有详细信息和代码示例中使用它.即使以后.NET 4.0并不需要它,也可能仅对理解有所帮助: ^ ].

—SA
This scheme looks complicated and too much of ad-hoc at the same time. I''m almost sure your design is not well thought just yet. This is where you should better start. You want to create dependencies between thread through thread synchronization directly, which can easily mess up things.

One important technique you should consider is the producer-consumer design pattern. Please see: http://en.wikipedia.org/wiki/Producer-consumer_problem[^].

In .NET starting from v.4.0, the implementation can be based on the generic collection System.Collections.Concurrent.BlockingCollection. Please see:
http://msdn.microsoft.com/en-us/library/dd997371%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/dd267312%28v=vs.110%29.aspx[^].

For earlier versions of .NET BCL, and even for versions 4.0 or later, please see my article where I implement such a blocking queue and explain how is it used in all the detail and code samples. Even though it is not really needed for .NET 4.0 later, it could be helpful for just for understanding things: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].

—SA


这篇关于如何在另一个线程启动时停止主线程&在第二个线程停止后恢复主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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