Suspending a thread from another thread

M

Max

Hello,

I made an application that uses the main thread for the UI, and another thread to communicate through the RS232 port. I would
like the communication thread to be suspended immediately when the user presses the ESC key. It should resume when the user answers
a dialog box. The Thread.Suspend cannot be used anymore in .NET and I'm trying to figure out how to do this differently. Can anyone
help?

Cheers,
Max.
 
S

Samuel R. Neff

Use a ManualResetEvent.

The RS232 thread should wait on this event regularly within it's
communication loop. Leave the event will be in Set state. When the
user presses ESC in the UI thread Reset the event and the RS232 will
wait the next time it gets to a WaitOne call (so you have to call
WaitOne within your communication loop as often as possbile).

Then when the UI thread answers the dialog call ManualResetEvent.Reset
and the RS232 thread will continue.

HTH,

Sam
 
B

Ben Voigt

Max said:
Hello,

I made an application that uses the main thread for the UI, and another
thread to communicate through the RS232 port. I would like the
communication thread to be suspended immediately when the user presses the
ESC key. It should resume when the user answers a dialog box. The
Thread.Suspend cannot be used anymore in .NET and I'm trying to figure out
how to do this differently. Can anyone help?

In reality, there's no need for a separate thread to accomplish what you
describe. Windows serial ports fully support overlapped I/O completion
callbacks. However the serial port class in the .NET Framework BCL doesn't
expose this functionality, and the .NET message loop doesn't wait alertably,
so you can't even implement this single threaded design via P/Invoke.

However, using overlapped I/O with completion callbacks is entirely possible
in your second thread, then you use an alertable wait
(WaitForSingleObjectEx) to wait for I/O events to occur, or if you set your
suspend/exit event. If you need more wakeup conditions, there's also
WaitForMultipleObjectsEx.

Another way, requiring Vista, is to P/Invoke CancelIoEx to interrupt your
current I/O operation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top