c# - Implementing 'await' type behavior to non-awaitable task -


there difference in apis windows phone 8 , standard .net when accessing wcf services. api wp8 forces use of callbacks rather offering awaitable interface. furthermore, use custom headers service calls include shenanigans different on these 2 platforms (i prefer code runnable on both though).

anyway, ended pattern similar this:

    private bool moperationcompleted = false;     private operationresulttype moperationresult;      public async task<operationresulttype> wcfservicerequestoperationname()     {         mclient.wcfservicerequestoperationnamecompleted += wcfservicerequestoperationnamecompleted;          performrequest(mclient, () => mstoreclient.wcfservicerequestoperationname(dem parameters particular call));          while (!moperationcompleted ) { await task.delay(500); /* delay isn't mandatory here */ }          // reset         moperationcompleted = false;          // return         return moperationresult;     }      void client_wcfservicerequestoperationnamecompleted(object sender, wcfservicerequestoperationnamecompletedeventargs e)     {         moperationresult = e.result;         moperationcompleted = true;     } 

mclient here servicereferenceclient generated vs2012. when await async operation, 'await-like' behavior; i.e.

var result = await wcfservicerequestoperationname(); 

so problem is, how wrap pattern in class can call in generic fashion wcf service call. generics , delegates might have solution this, can't pass events parameters, don't know how can add handler in generic fashion.

i want this, because not want copy-paste , adjust every request make.

you don't want use polling pattern wcf calls. instead, follow standard pattern wrapping eap members in tap methods. make them extension methods, they're written once , can used anywhere:

public static task<operationresult> operationtaskasync(this wcfservice client) {   var tcs = new taskcompletionsource<operationresult>();   operationcompletedeventhandler handler = null;   handler = (_, e) =>   {     client.operationcompleted -= handler;     if (e.error != null)       tcs.trysetexception(e.error);     else if (e.cancelled)       tcs.trysetcanceled();     else       tcs.trysetresult(e.result);   };   client.operationcompleted += handler;   client.operationasync();   return tcs.task; } 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -