Friday, 15 May 2015

c# - Cancel task and wait for it to finish -



c# - Cancel task and wait for it to finish -

i have time consuming task need run in separate thread avoid locking gui thread. task progresses, updates specific gui control.

the grab user might move part of gui before task over, , in case, have to:

cancel ongoing task (if active) wait till it's done cancelling: crucial, because time consuming task's objective update specific control. if more 1 thread tries @ once, things might messy. launch task scratch

for concrete example, imagine form has 2 parts: 1 navigate directory tree, , display thumbnails. when user navigates directory, thumbnails need refreshed.

first thought of using backgroundworker , autoresetevent wait cancellation, must have messed because got deadlocked when cancelling. read tpl, supposed replace bgw , more primitive mechanisms.

can done using tpl?

a few things note:

you can cancellationtoken cancellationtokensource

task cancellation cooperative action: if task not periodically check cancellationtoken.iscancellationrequested property, doesn't matter how many times seek cancel task, merrily churn away.

those things said, here's general idea:

void main() { var tokensource = new cancellationtokensource(); var mytask = task.factory .startnew(() => dowork(tokensource.token), tokensource.token); thread.sleep(1000); // ok, let's cancel (well, let's "request cancelled") tokensource.cancel(); // wait task "finish" mytask.wait(); } public void dowork(cancellationtoken token) { while(!token.iscancellationrequested) { // useful stuff here console.writeline("working!"); thread.sleep(100); } }

c# task-parallel-library

No comments:

Post a Comment