Making a request synchronouslyhttp://forums.asp.net/t/1772530.aspx/1?Making+a+request+synchronouslyTue, 13 Mar 2012 18:53:54 -040017725304845207http://forums.asp.net/p/1772530/4845207.aspx/1?Making+a+request+synchronouslyMaking a request synchronously <p>Hi everyone,</p> <p>&nbsp; Just started using Web API during preview 6 then my world got flipped upside when things shifted to the ASP.NET Web API!</p> <p>&nbsp; I wanted to get some opinions on some code I wrote usign Web API and if there were any ways I could improve it. &nbsp;Basically, I don't think that I&nbsp;<em>need</em> any of the async stuff right now, and don't want to upgrade and wait for .NET 4.5 to be released. &nbsp;I just want the code to run like it did during preview 6.</p> <p>&nbsp; So how does this code look to you guys/gals? &nbsp;All it does is attempt to read a concrete type from the response stream. &nbsp;For some reason, this code didn't work with the built in ReadAsAsync&lt;T&gt; code handling the serialization, so I instead used the Newtonsoft JSON library:</p> <pre class="prettyprint">public T GetDataFromService&lt;T&gt;() { using (var httpClient = new HttpClient()) { T result = default(T); Task&lt;HttpResponseMessage&gt; responseTask = null; httpClient.GetAsync(_endpoint).ContinueWith((requestTask) =&gt; { responseTask = requestTask; HttpResponseMessage response = requestTask.Result; response.EnsureSuccessStatusCode(); response.Content.ReadAsStringAsync().ContinueWith((readTask) =&gt; { result = JsonConvert.DeserializeObject&lt;T&gt;(readTask.Result); }); }); // HACK: My version of the await keyword while (responseTask == null || !responseTask.IsCompleted || result == null) { } return result; } }</pre> 2012-02-22T12:30:27-05:004845234http://forums.asp.net/p/1772530/4845234.aspx/1?Re+Making+a+request+synchronouslyRe: Making a request synchronously <p>You can call .Result on a Task to wait for the result.</p> <pre class="prettyprint">using (var httpClient = new HttpClient()) { var response = httpClient.GetAsync(_endpoint).Result; var result = response.Content.ReadAsStringAsync().Result; /*ToDo: Parse Json*/ return result; }</pre> 2012-02-22T12:48:50-05:004845269http://forums.asp.net/p/1772530/4845269.aspx/1?Re+Making+a+request+synchronouslyRe: Making a request synchronously <p>Nice! &nbsp;I didn't realize you could get the Result immediately like that, which I assumes just blocks the current thread while waiting. &nbsp;Awesome!</p> <p>This is the simple code that I've been looking for!</p> 2012-02-22T13:10:27-05:004845452http://forums.asp.net/p/1772530/4845452.aspx/1?Re+Making+a+request+synchronouslyRe: Making a request synchronously <p>I shortened it up a little further, here is the complete generic method for a Get request:</p> <pre class="prettyprint">public T GetDataFromService&lt;T&gt;() { using (var httpClient = new HttpClient()) { var response = httpClient.GetAsync(_endpoint).Result; return JsonConvert.DeserializeObject&lt;T&gt;(response.Content.ReadAsStringAsync().Result); } }</pre> 2012-02-22T14:26:16-05:004845500http://forums.asp.net/p/1772530/4845500.aspx/1?Re+Making+a+request+synchronouslyRe: Making a request synchronously While .Result works note that by using it you are losing all the perf benefits that Task provides. When you block a thread your server will not be able to use it to serve other requests meaning you lose scalability. I'd recommend returning Task&lt;T&gt; instead. 2012-02-22T14:54:36-05:004845916http://forums.asp.net/p/1772530/4845916.aspx/1?Re+Making+a+request+synchronouslyRe: Making a request synchronously <p>Yeah, thanks for the heads up. &nbsp;That thought definitely crossed my mind, but this is for an internal business app, so there will never be the need to scale (I hope). &nbsp;So for now I'll do it the hacky way, but then I'll definitely switch back to async when the .NET 4.5 comes out.</p> 2012-02-22T20:40:40-05:004846340http://forums.asp.net/p/1772530/4846340.aspx/1?Re+Making+a+request+synchronouslyRe: Making a request synchronously <p>if you like RX, (which I like), the following code fragment sample using Async as follows:</p> <pre class="prettyprint">GetData(myuri).ObserveOnDispatcher().Subscribe((o) =&gt; { XmlSerializer xs = new XmlSerializer(typeof(List&lt;T&gt;)); var data = xs.Deserialize(o.GetResponseStream()) as List&lt;T&gt;; }); public static IObservable&lt;WebResponse&gt; GetData(Uri uri) { var request = (HttpWebRequest)WebRequestCreator.BrowserHttp.Create(uri); request.Method = &quot;GET&quot;; request.Accept = &quot;text/xml&quot;; var observer = Observable.FromAsyncPattern&lt;WebResponse&gt;(request.BeginGetResponse, request.EndGetResponse); return observer(); }</pre> 2012-02-23T05:10:13-05:004878257http://forums.asp.net/p/1772530/4878257.aspx/1?Re+Making+a+request+synchronouslyRe: Making a request synchronously <p>Marcind,</p> <p>Unless the complete pipeline (that is from<strong>&nbsp;</strong>Page or Handler onwards) is async, you won't get the perf benefits you're talking about as regards the Web Server using I/O completetion ports and being able to serve other requests because threads are freed up.</p> <p>From the OP's example, it looks like the method doing the service call it a synchronous call. So at some point during the Request-Response cycle, things are not async all the way. So you're point is moot.</p> 2012-03-13T18:53:54-04:00