c# - Communicate to the UI thread when a thread completes -
i have simple program here below has 2 threads performing task.
thread1 data feeder. thread2 data processor.
so far work being done through approach working want have better way of getting notified when work completes
here code
class program { private static blockingcollection<int> _samples = new blockingcollection<int>(); private static cancellationtokensource _cancellationtokensource = new cancellationtokensource(); private static bool _cancel; static void main(string[] args) { threadstart thread1 = delegate { processthread1(); }; new thread(thread1).start(); threadstart thread2 = delegate { processthread2(); }; new thread(thread2).start(); console.writeline("press key cancel.."); console.read(); _cancel = true; _cancellationtokensource.cancel(); console.read(); } private static void processthread1() { (int = 0; < 10; i++) { if (_cancel) { break; } console.writeline("adding data.."); _samples.tryadd(i,100); thread.sleep(1000); } // dont this. instead can notified in ui thread thread complete. _cancel = true; _cancellationtokensource.cancel(); } private static void processthread2() { while (!_cancellationtokensource.iscancellationrequested) { int data; if (_samples.trytake(out data, 100)) { // work. console.writeline("processing data.."); } } console.writeline("cancelled."); } }
i want program exit if cancel requested user or when work completes.
i not sure how can notified when processthread1 runs out of work. setting cancel = true when work complete seem not right. appreciated.
if use task
instead of manually creating threads, can attach continuation on task notify ui work complete.
task workone = task.factory.startnew( () => processthread1()); workone.continuewith(t => { // update ui here }, taskscheduler.fromcurrentsynchronizationcontext());
with .net 4.5, becomes easier, can potentially use new async
language support:
var workone = task.run(processthread1); var worktwo = task.run(processthread2); // asynchronously wait both tasks complete... await task.whenall(workone, worktwo); // update ui here.
note these both designed user interface in mind - , behave unusually in console application, there no current synchronization context in console application. when move true user interface, behave correctly.
Comments
Post a Comment