c# - TPL and Monitor in PCL -


so i'm writing client api pcl (.net 4.5, sl 5, win8, wp8.1, wp sl 8) library , i've decided i'm going allow 1 http request @ time. use tpl them:

task.factory.fromasync<stream>(httpreq.begingetrequeststream, httpreq.endgetrequeststream, null).continuewith<task<webresponse>>((requeststreamtask) => {     return task<webresponse>.factory.fromasync(httpreq.begingetresponse, httpreq.endgetresponse, null); }).unwrap().continuewith<httpwebresponse>((getresponsetask) =>     {         return (httpwebresponse)getresponsetask.result;     }); 

so want add locking prevent more 1 request going @ once. know call monitor.enter before start , call monitor.exit in last continuewith. based on migrating lock tpl, can't use monitor because of threading issues possibly. have no issue using different blocking object post recommends far can tell in pcl lock have available monitor.

so should do?

edit: after talking yuval itzchakov below i've realized reason have monitor class syncing because have silverlight 5 support in pcl. if there no other way i'll dropping support sl5 i'd rather not.

edit2: after messing around realized have manualresetevent class, use that?

since you're writing pcl , including older platforms (specifically, sl5), choices bit limited. tpl dataflow not supported on sl5, , neither semaphoreslim.

however, httpclient is, , so async/await. these allow code far, far cleaner task.factory.fromasync + unwrap + continuewith.

for portable async-ready synchronization and/or producer/consumer queues, recommend own asyncex library. in case, asynclock should suffice; can used in similar way semaphoreslim:

private readonly httpclient _client = new httpclient(); private readonly asynclock _mutex = new asynclock();  public async task<string> getstringasync(string url) {     using (await _mutex.lockasync())     {         return await _client.getstringasync(url);     } } 

Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -