Asynchronous call with a static method in C# .NET 2.0 -
i have .net 2.0 application. in application, need pass info server. server exposes rest-based url can post info to. when pass info server, need asynchronously, , other times need blocking call. in scenario of asynchronous call, need know when phone call completed. point understand how do.
where problem is, method working on must static. it's code i've inherited, , i'd rather not have redo of code. currently, have 2 static methods:
public static string senddata (...) { } public static string senddataasync(...) { }
the string
returned response code server. static part giving me fits. doesn't cause problem in blocking version. however, in competition of asynchronous call, i'm not sure do.
does have insights can provide?
this general async pattern before c# 5 (iirc).
public static string senddata (...) { } public static iasyncresult beginsenddata(..., asynccallback cb) { var f = new func<..., string>(senddata); homecoming f.begininvoke(..., cb, f); } public static string endsenddata(iasyncresult ar) { homecoming ((func<..., string>) ar.asyncstate).endinvoke(ar); }
usage:
beginsenddata(..., ar => { var result = endsenddata(ar); // result });
full console example:
public static string senddata(int i) { // sample payload thread.sleep(i); homecoming i.tostring(); } public static iasyncresult beginsenddata(int i, asynccallback cb) { var f = new func<int, string>(senddata); homecoming f.begininvoke(i, cb, f); } public static string endsenddata(iasyncresult ar) { homecoming ((func<int, string>)ar.asyncstate).endinvoke(ar); } static void main(string[] args) { beginsenddata(2000, ar => { var result = endsenddata(ar); console.writeline("done: {0}", result); }); console.writeline("waiting"); console.readline(); }
the above print:
waiting done: 2000
c# asynchronous .net-2.0
No comments:
Post a Comment