/// <summary> /// Read packets off the string asynchronously. /// </summary> /// <returns>Task that will make the read.</returns> /// <see cref="http://stackoverflow.com/questions/4388771/difference-between-networkstream-read-and-networkstream-beginread"/> /// <see cref="http://www.winsocketdotnetworkprogramming.com/threadingasynchronouspatterninnetwork3g.html"/> /// <see cref="http://msdn.microsoft.com/en-us/library/dd997423.aspx"/> /// <see cref="http://www.albahari.com/nutshell/cs4ch23.aspx"/> public Task<string> ReadAsync() { byte[] buffer = new byte[5000]; // this will create a child task Task<int> readTask = Task<int>.Factory.FromAsync( this.networkStream.BeginRead, this.networkStream.EndRead, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent); // run this when the readtask is done return readTask.ContinueWith((originalReadTask) => { string data = new UTF8Encoding().GetString(buffer); // there's possibly more than 5000 bytes to read, so get the next section of the response string remaining = string.Empty; if (!data.EndsWith("\0") && readTask.Result == buffer.Length) { remaining = Read(); } return string.Concat(data, remaining); }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent); }