First of all, this is not called "suspend" and "resume". You need just a blocking call, blocking the thread until some condition, such as data ready. The methods blocking threads are the methods which put a thread in a special wait state when they are not use any CPU time until waken up. To have this with a serial port, you don't need anything special. You can just read some bytes using one of the
System.IO.Ports.SerialPort.Read
or
Read*
methods:
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport%28v=vs.110%29.aspx[
^].
However, there is a very delicate problem here. Everything would work perfectly if you, for example, use
ReadByte
. Then your calling thread will be blocked, put to a wait state and not scheduled back to execution until it is waken up by some condition. It could be abort, timeout, or the byte arrived to the buffer, whichever comes first. All as you need. To read other bytes, read in "infinite" cycle. The thread will be either working and getting data all the time, or it will be put to the wait state.
However, the performance of such a simple solution may be insufficient, so you may need to read to the
byte[]
buffer:
http://msdn.microsoft.com/en-us/library/ms143549(v=vs.110).aspx[
^].
Here is when you need to use caution. Here is why: your calling thread will be unblocked (waken up) even if you receive less bytes than you expected, because your thread will be waken up is only part of the data arrives. In other words, the mechanism of the transport and thread waking does not care how much data you requested, and your buffer will be incomplete, which may cause loss of data unless you take care about that.
This is explained here:
https://netmf.codeplex.com/workitem/1633[
^].
What to do then? The idea is explained above, but let me make it clear: pay attention that the
Read
method referenced above returns the
number or actually transmitted bytes. Using this number, you should infer if the operation is complete or not, and read more, in a cycle.
One more advice: better don't read characters instead of bytes, as the characters are the Unicode characters, may be represented in one or another UTF or ASCII, and so on, so you may receive more then one byte per character —
unless you know perfectly what you are doing. It would be safer to read bytes and later deserialize them to string using one of the encodings:
http://msdn.microsoft.com/en-us/library/system.text.encoding%28v=vs.110%29.aspx[
^].
[EDIT]
I also want to explain on thread "suspending" and "resuming" operations. They have been deprecated and are no longer supported, because are quite unsafe. Do you understand why? Instead, similar behavior can be achieved in the safe way by using event wait handles.
For understanding (your problem does not require using such things) please see my past answers:
Security on my developed dll[
^],
pause running thread[
^],
ManualResetEvent and AutoResetEvent in Thread[
^],
Making Code Thread Safe[
^].
—SA