Alex Rivera | Logout

Continuously reading from a stream?

Asked 2010-05-06T22:13:24.287
16

I have a Stream object that occasionally gets some data on it, but at unpredictable intervals. Messages that appear on the Stream are well-defined and declare the size of their payload in advance (the size is a 16-bit integer contained in the first two bytes of each message).

I'd like to have a StreamWatcher class which detects when the Stream has some data on it. Once it does, I'd like an event to be raised so that a subscribed StreamProcessor instance can process the new message.

Can this be done with C# events without using Threads directly? It seems like it should be straightforward, but I can't get quite get my head around the right way to design this.

Edit
Report

2 Answers

1

The normal approach is to use the .NET asynchronous programming pattern exposed by Stream. Essentially, you start reading asynchronously by calling Stream.BeginRead, passing it a byte[] buffer and a callback method that will be invoked when data have been read from the stream. In the callback method, you call Stream.EndRead, passing it the IAsncResult argument that was given to your callback. The return value of EndRead tells you how many bytes were read into the buffer.

Once you've received the first few bytes in this way, you can then wait for the rest of the message (if you didn't get enough data the first time round) by calling BeginRead again. Once you've got the whole message, you can raise the event.

answered 2010-05-06T22:29:16.403
1

Isn't using Stream.BeginRead() same like using the synchronous Stream.Read() method in a separate thread?

answered 2010-11-25T17:46:16.317

Your Answer