Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Good call with the enumerators, although I hope that your outer code isn't just calling WaitOne on the asyncresults as this would block the running thread. </p> <p>If you like that style of async coding check out Wintellect AsyncEnumerator on NuGet - it uses iterators too, makes the code very resource efficient and adds easier ways to handle cancellation and exceptions while makings sure APM end methods all get called.</p> <p>I've previously addressed the exact read problem by:</p> <p>1) Adding a length prefix to data sent on the socket<br> 2) Defining a helper class that works on a Socket with the following methods: </p> <pre><code>public IAsyncResult BeginRead(AsyncCallback callback) // Calculate whether to read length header or remaining payload bytes // Issue socket recieve and return its IAsyncResult public MemoryStream EndRead(IAsyncResult result) // Process socket read, if payload read completely return as a memorystream // If length header has been recieved make sure buffer is big enough // If 0 bytes recieved, throw SocketException(10057) as conn is closed public IAsyncResult BeginSend(AsyncCallback callback, MemoryStream data) // Issue sends for the length header or payload (data.GetBuffer()) on the first call public Boolean EndSend(IAsyncResult result) // Process bytes sent, return true if payload sent completely. // If 0 bytes sent, throw SocketException(10057) </code></pre> <p>So it still needs to be called in a loop but looks like a normal async operation, e.g. called via asyncenumerator (without cancellation checks and exception handling):</p> <pre><code>do { socketHelper.BeginSend(ae.End(1, ar =&gt; socketHelper.EndSend(ar)), sendData); yield return 1; doneSend = socketHelper.EndSend(ae.DequeueAsyncResult()); } while (!doneSend); </code></pre>
 

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