15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

exception is encountered, it’s no good writing it to the Console; we need to throw<br />

it back to the consumer at some point. So, to usefully partake in the pattern, we<br />

must also offer EndReverseEcho and write a class that implements IAsyncResult.<br />

Our ReverseEcho class is an excellent candidate for IAsyncResult, since it already<br />

encapsulates the operation’s state. All we really need to add is some plumbing code<br />

to rethrow any exception upon calling EndReverseEcho, and a wait handle to signal<br />

at completion.<br />

Here’s a real-world example, complete with exception handling and thread safety:<br />

// This sample can be downloaded at http://www.albahari.com/nutshell/<br />

public class MessagingServices<br />

{<br />

public static IAsyncResult BeginReverseEcho (TcpClient client,<br />

AsyncCallback callback,<br />

object userState)<br />

{<br />

var re = new ReverseEcho();<br />

re.Begin (client, callback, userState);<br />

return re;<br />

}<br />

public static byte[] EndReverseEcho (IAsyncResult r)<br />

{<br />

return ((ReverseEcho)r).End();<br />

}<br />

}<br />

class ReverseEcho : IAsyncResult<br />

{<br />

TcpClient _client;<br />

NetworkStream _stream;<br />

object _userState;<br />

ManualResetEvent _waitHandle = new ManualResetEvent (false);<br />

int _bytesRead = 0;<br />

byte[] _data = new byte [5000];<br />

Exception _exception;<br />

internal ReverseEcho() { }<br />

// IAsyncResult members:<br />

public object AsyncState { get { return _userState; } }<br />

public WaitHandle AsyncWaitHandle { get { return _waitHandle; } }<br />

public bool CompletedSynchronously { get { return false; } }<br />

public bool IsCompleted<br />

{<br />

get { return _waitHandle.WaitOne (0, false); }<br />

}<br />

internal void Begin (TcpClient c, AsyncCallback callback, object state)<br />

{<br />

_client = c;<br />

_userState = state;<br />

938 | Chapter 23: Asynchronous Methods

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!