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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

_stream = _client.GetStream();<br />

Task.Factory.StartNew (Read).ContinueWith (ant =><br />

{<br />

_exception = ant.Exception; // In case an exception occurred.<br />

if (_stream != null)<br />

try { _stream.Close(); }<br />

catch (Exception ex) { _exception = ex; };<br />

_waitHandle.Set();<br />

if (callback != null) callback (this);<br />

});<br />

}<br />

internal byte[] End() // Wait for completion + rethrow any error.<br />

{<br />

AsyncWaitHandle.WaitOne();<br />

if (_exception != null) throw _exception;<br />

return _data;<br />

}<br />

void Read()<br />

{<br />

Task readChunk = Task.Factory.FromAsync (<br />

_stream.BeginRead, _stream.EndRead,<br />

_data, 0, _data.Length - _bytesRead, null);<br />

}<br />

readChunk.ContinueWith (ContinueRead,<br />

TaskContinuationOptions.NotOnFaulted);<br />

void ContinueRead (Task readChunk)<br />

{<br />

_bytesRead += readChunk.Result;<br />

if (readChunk.Result > 0 && _bytesRead < _data.Length)<br />

{<br />

Read(); // More data to read!<br />

return;<br />

}<br />

Array.Reverse (_data);<br />

Task.Factory.FromAsync (_stream.BeginWrite, _stream.EndWrite,<br />

_data, 0, _data.Length, null);<br />

}<br />

}<br />

In Cleanup, we closed _stream but not _client, because the caller may want to continue<br />

using _client after performing the reverse echo.<br />

Writing Asynchronous Methods | 939<br />

Asynchronous<br />

Methods

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

Saved successfully!

Ooh no, something went wrong!