问题描述
你好。我又回到了线程演出。这是一个古老的问题,关于等待事情发生而不是
浪费时间做它。
采取两个线程:主线程和工作线程。工作线程是
读取串口,等待事情发生(服务
请求)。当它发生时它会引发一个事件。当然,在工作线程上执行事件
。这个想法是,当事件被引发时,处理程序
在串口发出命令并等待响应。问题是
,工作线程的一部分(用于回复)是
与它刚刚提出的事件捆绑在一起,因此无法监听
最新回复。
所以,我认为当事件发生时,我需要设置一个标志,
可以在主线程上获取。这样事件完成后,
工作线程回到侦听回复,主线程看到
标志并发出命令。
听起来不错,但现在我必须定期检查主要的
线程中的标志。这对我来说听起来非常糟糕,而且我不想浪费时间来投票。
我怎样才能抓住主线程何时发生变化,没有
坐下等待它?
像往常一样,关于如何做到这一点的任何建议总是受欢迎的,
但是很激进。
TIA
Charles
我害怕我没有密切关注你的例子,但听起来像你基本上想要Monitor.Wait和Monitor.Pulse这样的b $ b。
我有一篇未完成的文章谈论它们(以及其他的b $ b b) - 它在
当我接触到它时,还有更多的东西,但是更多
监视方法中的位描述等待和脉冲。
(你也可以使用ManualResetEvent或AutoResetEvent。)
-
Jon Skeet - < sk *** @ pobox.com>
如果回复小组,请不要给我发邮件
Hi guys. I''m back on the threading gig again.
It''s the age-old question about waiting for something to happen without
wasting time doing it.
Take two threads: the main thread and a worker thread. The worker thread is
reading the serial port, waiting for something to happen (a service
request). When it does it raises an event. Of course, the event is executed
on the worker thread. The idea is that when the event is raised, the handler
issues a command on the serial port and waits for a response. The problem is
that the part of the worker thread that does the listening (for replies) is
tied up with the event it has just raised, and therefore cannot listen for
the latest reply.
So, I think that when the event is raised, I need to set a flag perhaps,
that can be picked up on the main thread. This way the event completes, the
worker thread goes back to listening for replies, and the main thread sees
the flag and issues its command.
Sounds good, but now I have to periodically check for the flag in the main
thread. That sounds an awful lot like polling to me, and I don''t want to
waste time polling.
How can I catch the flag in the main thread when it changes, without having
to sit and wait for it?
As usual, any suggestions about how else to do this are always welcome,
however radical.
TIA
Charles
I''m afraid I didn''t follow your example very closely, but it sounds
like you basically want Monitor.Wait and Monitor.Pulse.
I''ve got an unfinished article which talks about them (and other
things) - it''s at
http://www.pobox.com/~skeet/csharp/multithreading.html
There''s more to come when I get round to it, but the bit in "More
Monitor methods" described Wait and Pulse.
(You could also use ManualResetEvent or AutoResetEvent.)
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
这篇关于等待线程 - 重访的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!