c# - What should I do to use Task<T> in .NET 2.0? -


.net 4.0 has tpl contains nice task class encapsulate aynchronous programming models. i'm working on app must .net 2.0, want avoid rewriting task. suggestions?

i know said dont want rewrite task, can create simple using closures, behaves task object. use:

    public delegate r asynctask<r>();      public static asynctask<r> begintask<r>(asynctask<r> function)     {         r retv = default(r);         bool completed = false;          object sync = new object();          iasyncresult asyncresult = function.begininvoke(                 iasyncresult =>                 {                     lock (sync)                     {                         completed = true;                         retv = function.endinvoke(iasyncresult);                         monitor.pulse(sync);                      }                 }, null);          return delegate         {             lock (sync)             {                 if (!completed)                                {                     monitor.wait(sync);                  }                 return retv;             }         };     } 

its function calls begininvoke() on delegate pass in, , returns function when called blocks , waits result of function passed in. you'd have create overloads of function different method signatures, of course.

one way go, can tweak needs, , add other behaviors continuations, etc. key use closures , anonymous delegates. should work in .net 2.0.

edit - here how use it:

    public static string helloworld()     {         return "hello world!";      }      static void main(string[] args)     {         var task = begintask(helloworld); // non-blocking call          string result = task(); // block , wait      } 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -