c# - Apply CancellationToken in dataflowblock -
in producer-consumer application. have:
cancellationtokensource ctokensource = new cancellationtokensource(); cancellationtoken ctoken = new cancellationtoken(); ctoken = ctokensource.token;
click start button, application running.
private async void start_click(object sender, routedeventargs e) { var producer = producer(); var consumer = consumer(); await task.whenall(producer, consumer); }
in consumer, used tpl.
async task consumer() { seek { var executiondataflowblockoptions = new executiondataflowblockoptions { maxdegreeofparallelism = 50, cancellationtoken = ctoken }; var consumerblock = new actionblock<appointmentreminder>( remainder => { // blah blah long running processes , updating ui var result = run(reminder); }, executiondataflowblockoptions); bufferblock.linkto( consumerblock, new dataflowlinkoptions { propagatecompletion = true }); await task.delay(500); }
now have cancel button, want stop tpl consumer tasks while click it. how?
private void cancel_click(object sender, routedeventargs e) {
cancellation in .net cooperative. create cancellationtokensource
handle cancellation , utilize cancellationtoken
notified of cancellation. cancel token phone call cancellationtokensource.cancel
:
ctokensource.cancel();
btw, there's no much utilize in creating cancellationtoken
straight can never cancelled. should token cancellationtokensource
:
var ctokensource = new cancellationtokensource(); var ctoken = ctokensource.token;
c# .net task-parallel-library cancellation
No comments:
Post a Comment