Share via


Streaming with WCF - Sidebar: What is really going on with my stream?

Streaming with WCF 

Sidebar - What is really going on with my stream?

This posting might not directly help you implement something, but it should give some insight as to what's going on under the hood with a stream sent to a client from a service.

 

Scenario

There's a WCF service with an operation which returns a Stream.

A WCF Client invokes this operation.

The Transfer Mode is Streamed.

 

So, here's what happens, diagram first:

 

 

 

To elaborate:

  1. The client call is received by the service. The service creates some custom stream in the operation and returns it.
  1. Because transfer mode is Streamed, the Encoder gets a wire stream handed to it from the transport layer.
  2. Using the wire stream and the stream handed from the service (which I'll call CustomStream from here on), the encoder then begins to create a message. It starts with all the Soap stuff, but when it comes to the body, it starts the streamed transfer. It calls a method which takes the two streams. This method basically gets a buffer from the wire stream and fills it up with bytes from the CustomStream. Then it calls Write on the wire stream, passing the buffer. This is what sends the bytes out on the wire. If the Read call on the CustomStream returned exactly the same value as that buffer, then we know there are more bytes to write. To make things more efficient, subsequent Read calls get a larger buffer allocated.

 

What if I used TransferMode.Buffered?

Instead of the Transport giving the WireStream to the encoder, the encoder will simply read the entire  CustomStream, package it up in a single message, and hand that message off to the transport which will then send it on the wire.  If your implementation is actually returning very small streams with many client calls, this might actually be optimal.  Otherwise, TransferMode.Streamed is the better option.