Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create an async method in C# 4 according to the best practices?
    primarykey
    data
    text
    <p>Consider the following code snippet:</p> <pre><code>public static Task&lt;string&gt; FetchAsync() { string url = "http://www.example.com", message = "Hello World!"; var request = (HttpWebRequest)WebRequest.Create(url); request.Method = WebRequestMethods.Http.Post; return Task.Factory.FromAsync&lt;Stream&gt;(request.BeginGetRequestStream, request.EndGetRequestStream, null) .ContinueWith(t =&gt; { var stream = t.Result; var data = Encoding.ASCII.GetBytes(message); Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, data, 0, data.Length, null, TaskCreationOptions.AttachedToParent) .ContinueWith(t2 =&gt; { stream.Close(); }); }) .ContinueWith&lt;string&gt;(t =&gt; { var t1 = Task.Factory.FromAsync&lt;WebResponse&gt;(request.BeginGetResponse, request.EndGetResponse, null) .ContinueWith&lt;string&gt;(t2 =&gt; { var response = (HttpWebResponse)t2.Result; var stream = response.GetResponseStream(); var buffer = new byte[response.ContentLength &gt; 0 ? response.ContentLength : 0x100000]; var t3 = Task&lt;int&gt;.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent) .ContinueWith&lt;string&gt;(t4 =&gt; { stream.Close(); response.Close(); if (t4.Result &lt; buffer.Length) { Array.Resize(ref buffer, t4.Result); } return Encoding.ASCII.GetString(buffer); }); t3.Wait(); return t3.Result; }); t1.Wait(); return t1.Result; }); } </code></pre> <p>It should return <code>Task&lt;string&gt;</code>, send HTTP POST request with some data, return a result from webserver in a form of string and be as much efficient as possible.</p> <ul> <li>Did you spot any problems regarding async flow in the example above?</li> <li>Is it OK to have .Wait() inside .ContinueWith() in this example</li> <li>Do you see any other problems with this peace of code (keeping aside exception handling for now)?</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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