c# - Migrating lock to TPL -
in normal c# write
int dosomething(){/*...*/)}; lock(mutex) { return dosomething(); }
to ensure in cases mutex
released.
but if signature of dosomething
changed to
task<int> dosomethingasync(){/*...*/};
does following code
return task.factory.startnew(() => { monitor.enter(mutex); return dosomethingasync(); }).unwrap().continuewith(t => { monitor.exit(mutex); return t; }).unwrap();
do similar things? guaranteed release mutex
whenever entered? there simpler way so? (i not able use async
keyword keep thinking in tpl only)
you can't use monitor
in way because monitor
thread-affine , in case task , continuation may run on different threads.
the appropriate synchronization mechanism use semaphoreslim
(which isn't thread-affine) set 1:
public semaphoreslim _semaphore = new semaphoreslim(1,1); _semaphore.wait(); return dosomethingasync().continuewith(t => { _semaphore.release(); return t.result; });
as long don't use 1 of taskcontinuationoptions
such onlyonfaulted
or onlyoncanceled
continuation run after task has completed , semaphore guaranteed released.
Comments
Post a Comment