c# - Stopping Multiple Tasks -
i'm using following method create new tasks , long time taking operations in background.if condition met,i need stop tasks , show user message.
dowork() { mylist = new list<datamodel.checkdata>(); int index = 0; foreach (var line in mylist) { mylist.add(new datamodel.checkdata() { rawline = line, data = line,filename=virtualfilelist[index].tostring() }); index++; } blockingcollection<datamodel.checkdata> ujobs = new blockingcollection<datamodel.checkdata>(); timerrefreshui.start(); task.factory.startnew(() => { _dtrows.clear(); uiqueue.clear(); uiqueuebad.clear(); uiqueuegood.clear(); (int = 0; < mylist.count; i++) { addresultrow(mylist[i].data, "waiting...",mylist[i].filename, color.white); ujobs.tryadd(new datamodel.checkdata() { rowid = i, data = mylist[i].data }, 1000); } list<task> openchecktasks = new list<task>(); while (ujobs.count > 0) { while (openchecktasks.where(task => task.status == taskstatus.running).tolist().count >= threadcount) system.threading.thread.sleep(250); task t = new task(new action(() => { })); openchecktasks.add(t); t.start(); } task.waitall(openchecktasks.toarray()); }).continuewith(task => { _benchmark.stop(); this.begininvoke(new action(() => { })); }); }
i have tried using cancellation token
, break
in while loop.but not working properly.please advice best way stop threads.i have little experience multiple thread programming.
cancellationtoken
right way go.
are trying control how many tasks run @ once? that's tpl does, , well.
see example starting many cpu intensive tasks, cancels of them after 3 seconds:
public static void main() { var delay = timespan.fromseconds(1); var cts = new cancellationtokensource(); var tasks = enumerable.range(0, 100).select(i => task.run(() => slowsqrt/*async*/(i, delay, cts.token), cts.token)).toarray(); thread.sleep(3000); cts.cancel(); } public static double slowsqrt(double arg, timespan delay, cancellationtoken token) { console.writeline($"calculating sqrt({arg})..."); var burncputimeuntil = datetime.now + delay; while (datetime.now < burncputimeuntil) token.throwifcancellationrequested(); var result = math.sqrt(arg); console.writeline($"sqrt({arg}) {result}."); return result; } public static async task<double> slowsqrtasync(double arg, timespan delay, cancellationtoken token) { console.writeline($"calculating sqrt({arg})..."); await task.delay(delay, token); var result = math.sqrt(arg); console.writeline($"sqrt({arg}) {result}."); return result; }
the output of is:
calculating sqrt(1)... calculating sqrt(2)... calculating sqrt(0)... calculating sqrt(3)... sqrt(2) 1.4142135623731. calculating sqrt(4)... sqrt(0) 0. calculating sqrt(5)... sqrt(3) 1.73205080756888. calculating sqrt(6)... sqrt(1) 1. calculating sqrt(7)... sqrt(5) 2.23606797749979. calculating sqrt(8)... sqrt(4) 2. calculating sqrt(9)... sqrt(6) 2.44948974278318. calculating sqrt(10)... sqrt(7) 2.64575131106459. calculating sqrt(11)...
as have 4 cores on machine, there 4 tasks being active @ time. tasks haven't started when token canceled (12..99) never kicked off. tasks started (8..11) error out in token.throwifcancellationrequested()
. of them end in taskstatus.canceled
state.
now if change above code invoke slowsqrtasync
, 1 second delay not use cpu, tpl activates 100 tasks, trying max cpu usage. 100 results after 1 second. if canceled task while inside task.delay
, throw operationcanceledexception
token.throwifcancellationrequested()
do.
calculating sqrt(0)... calculating sqrt(1)... : : calculating sqrt(92)... calculating sqrt(89)... (about 1 second later:) sqrt(19) 4.35889894354067. sqrt(5) 2.23606797749979. : : sqrt(99) 9.9498743710662. sqrt(92) 9.59166304662544.
Comments
Post a Comment