When you use threads, and use them properly, it renders asynchronous operations redundant; and using threads is a better way. I think asynchronous operations were invented when threads were not yet introduced (I remember, when I started to work with Linux, there were only processes, each process was single-threaded as thread API was not yet introduced; at that time Window NT was already released; and it has threads).
How to stop streaming? You can do streaming in some chunks of data. Between chunks you can poll a request status to see if there is a request to stop streaming; which should cause a break of the streaming loop. The request status should be interlocked between thread using thread synchronization. In this case, the best mechanism is probably
System.Threading.ReaderWriterLockSlim
because the request is often read but rarely written. See
http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx[
^]. The request is placed be the separate request thread which reads requests from a different network stream, the thread performing streaming is another thread.
Alternatively, you can abort streaming thread from the request thread using
Thread.Abort
. This is very safe mechanism (based on very clever exception seed mechanism), but it should be used with care. In particular, it's very important for the thread to be aborted to handle the exception
System.Threading.ThreadAbortException
to clean-up after abort. Failure to do proper clean-up can cause different unpleasant problems, even a deadlock.
—SA