c# - How to cancel a task from a TaskCompletionSource? -


i'm trying create async producerconsumercollection , that, i'm using msdn page (http://msdn.microsoft.com/en-us/library/hh873173.aspx (bottom of page)).

i'm trying add timeout, here :

    public async task<t> takewithtimeout(int timeout)     {             task<t> taketask = this.take();              if (timeout <= 0 || taketask == await task.whenany(this.tasks.take(), task.delay(timeout)))             {                 return await taketask;             }             else             {                 // timeout                 return default(t);             }         }     } 

the problem code that, in case of timeout, not cancel task created take() method.

since task has been "created" taskcompletionsource, cannot give cancellationtoken?

so, how proceed cancel , implement take timeout ?

thanks :)

writing cancel-safe async-friendly producer/consumer collection non-trivial. need change take accept cancellationtoken parameter, , should register handler when cancelled taskcompletionsource cancelled.

i highly recommend use bufferblock<t>, has cancellation support built-in.

if can't use tpl dataflow (e.g., you're working in pcl or have target platforms unsupported dataflow), can use producer/consumer collections in open-source asyncex library (such asyncproducerconsumerqueue or asynccollection). these both based on asynclock , asyncconditionvariable, design describe briefly on blog (which not cancellation details). key behind supporting cancellation in producer/consumer collection design support cancellation in asyncconditionvariable.waitasync; once condition variable type supports cancellation, collection support it, too.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -