Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Basically, when you call the <code>Begin*</code> method on an asynchronous operation, there needs to be a call to a corresponding <code>End*</code> statement (for more detailed information, see the <a href="http://msdn.microsoft.com/en-us/library/ms228963.aspx" rel="noreferrer">Asynchronous Programming Overview on MSDN</a>, specifically the section titled "Ending an Asynchronous Operation").</p> <p>That said, you generally want to pass a method/anonymous method/lambda expression which will do one or two things:</p> <p>1) Call the corresponding <code>End*</code> method, in this case, <a href="http://msdn.microsoft.com/en-us/library/system.io.stream.endread.aspx" rel="noreferrer"><code>Stream.EndRead</code></a>. This call will not block when called because the <code>callback</code> will not be called until the operation is complete (note that if an exception occurred during the async call then this exception will be thrown when the <code>End*</code> method is called).</p> <p>2) Possibly start a new asynchronous call. In this case, it's assumed you'll want to read more data, so you should start a new call to <a href="http://msdn.microsoft.com/en-us/library/system.io.stream.beginread.aspx" rel="noreferrer"><code>Stream.BeginRead</code></a></p> <p>Assuming you want to do #2, you can do the following:</p> <pre><code>// Declare the callback. Need to do that so that // the closure captures it. AsyncCallback callback = null; // Assign the callback. callback = ar =&gt; { // Call EndRead. int bytesRead = myNetworkStream.EndRead(ar); // Process the bytes here. // Determine if you want to read again. If not, return. if (!notMoreToRead) return; // Read again. This callback will be called again. myNetworkStream.BeginRead(buffer, offset, count, callback, null); }; // Trigger the initial read. myNetworkStream.BeginRead(buffer, offset, count, callback, null); </code></pre> <p>However, if you are using .NET 4.0, this becomes much easier using the <a href="http://msdn.microsoft.com/en-us/library/dd321404.aspx" rel="noreferrer"><code>FromAsync</code> method</a> on the <a href="http://msdn.microsoft.com/en-us/library/dd321401.aspx" rel="noreferrer"><code>TaskFactory</code> class</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload