c# - Notifying about task finishing its work -
i'm thinking of simple way of reacting on task finishing work. came following solution (paste winforms application single button test):
public partial class form1 : form { private thread thread; public void dofinishwork() { // [4] // ui thread - waiting thread finalize work thread.join(); // checking, if finished work messagebox.show("thread state: " + thread.isalive.tostring()); } public void dowork() { // [2] // working hard thread.sleep(1000); } public void finishwork() { // [3] // asynchronously notifying form in main thread, work done delegate del = new action(dofinishwork); this.begininvoke(del); // finalizing work - should switched // @ point main thread thread.sleep(1000); } public form1() { initializecomponent(); } private void button1_click(object sender, eventargs e) { // [1] // schedule task threadstart start = new threadstart(dowork); // schedule notification finishing work start += finishwork; thread = new thread(start); thread.start(); } }
this meant simple cancel scenario, there 1 thread, running in parallel ui thread.
is there simpler (or more thread-safe) way of implementing kind of notification thread
?
please take consideration 2 facts:
- the way can terminate thread
abort
(that's because have no control on being done in thread - 3rd party code) - thus, cannot use
backgroundworker
, because provides way of graceful termination.
is there simpler (or more thread-safe) way of implementing kind of notification thread?
yes, use tpl , let framework worry managing thread
task.startnew(() => { // stuff }).continuewith((task) => { // stuff after have finished doing other stuff });
or alternatively, since working winforms, use backgroundworker , handle runworkercompleted event.
i mistook notion of kill cancel - there no reliable way of killing thread in .net, documentation suggests using abort
more or less gamble , gives absolutely no guarentees thread killed. also, leave thread and, consequence, application in unpredictable state if willing take risk that's you.
one alternative let thread play out ignore results, depending on size of task might not big deal.
Comments
Post a Comment