parallel processing - How to create an async method in C# 4 according to the best practices? -


consider following code snippet:

public static task<string> 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<stream>(request.begingetrequeststream, request.endgetrequeststream, null)         .continuewith(t =>         {             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 => { stream.close(); });         })         .continuewith<string>(t =>         {             var t1 =                 task.factory.fromasync<webresponse>(request.begingetresponse, request.endgetresponse, null)                 .continuewith<string>(t2 =>                 {                     var response = (httpwebresponse)t2.result;                     var stream = response.getresponsestream();                     var buffer = new byte[response.contentlength > 0 ? response.contentlength : 0x100000];                     var t3 = task<int>.factory.fromasync(stream.beginread, stream.endread, buffer, 0, buffer.length, null, taskcreationoptions.attachedtoparent)                         .continuewith<string>(t4 =>                         {                             stream.close();                             response.close();                             if (t4.result < buffer.length)                             {                                 array.resize(ref buffer, t4.result);                             }                             return encoding.ascii.getstring(buffer);                         });                     t3.wait();                     return t3.result;                 });             t1.wait();             return t1.result;         }); } 

it should return task<string>, send http post request data, return result webserver in form of string , efficient possible.

  • did spot problems regarding async flow in example above?
  • is ok have .wait() inside .continuewith() in example
  • do see other problems peace of code (keeping aside exception handling now)?

if async related c# 4.0 code huge , ugly - there chance it's implemented properly. if it's nice , short, it's not ;)

..though, may more attractive creating extension methods on webrequest, stream classes , cleanup main method.

p.s.: hope c# 5.0 it's new async keyword , library released soon.

reference: http://msdn.microsoft.com/en-us/vstudio/async.aspx


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -