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.

...<br />

void MyCallback (IAsyncResult r)<br />

{<br />

int bytesRead;<br />

try { bytesRead = stream.EndWrite (r); }<br />

catch (Exception ex) { Console.Write (ex.Message); }<br />

Console.Write (bytesRead + " bytes read");<br />

}<br />

we can do this:<br />

var buffer = new byte[1000];<br />

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

stream.BeginRead, stream.EndRead, buffer, 0, 1000, null);<br />

readChunk.ContinueWith (ant => Console.Write (ant.Result + " bytes read"),<br />

TaskContinuationOptions.NotOnFaulted);<br />

readChunk.ContinueWith (ant => Console.Write (ant.Exception.Message),<br />

TaskContinuationOptions.OnlyOnFaulted);<br />

This doesn’t deliver a huge saving in itself: the real benefit comes when you introduce<br />

continuations with child antecedents. Revisiting our earlier example, suppose that<br />

we refactor ReverseEcho’s Begin method so that it calls Read on a new task. This<br />

liberates Server.Serve from having to create a task itself, but more importantly, it<br />

creates a parent for the FromAsync-created tasks upon which we can attach continuations.<br />

This avoids having to write separate exception-handling blocks or explicit<br />

fault continuations for each child task. Cleanup can also be done easily as another<br />

continuation on the parent:<br />

public class Server<br />

{<br />

public void Serve (IPAddress address, int port)<br />

{<br />

ThreadPool.SetMinThreads (50, 50);<br />

TcpListener listener = new TcpListener (address, port);<br />

listener.Start();<br />

while (true)<br />

{<br />

TcpClient c = listener.AcceptTcpClient();<br />

new ReverseEcho().BeginAsync (c);<br />

}<br />

}<br />

}<br />

class ReverseEcho<br />

{<br />

TcpClient _client;<br />

NetworkStream _stream;<br />

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

int _bytesRead = 0;<br />

internal void BeginAsync (TcpClient c)<br />

{<br />

_client = c;<br />

Asynchronous Methods and Tasks | 935<br />

Asynchronous<br />

Methods

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

Saved successfully!

Ooh no, something went wrong!