c# - Wake up a thread when event occurs -
i achieve following communication between 2 threads:
thread alpha something, , suspends itself. next second thread(beta) raises , event resumes alpha thread. cycle goes on...
i did below not sure if proper design. i've notice thread.suspend()
, thread.resume()
deprecated. i'm looking forward hearing advice implementation , preferred replace deprecated methods.
namespace threadtester { delegate void actionhandler(); class alpha { internal thread alphathread; internal void start() { while (true) { this.alphathread.suspend(); console.writeline("alpha"); } } internal void resume() { while (this.alphathread.threadstate == threadstate.suspended) this.alphathread.resume(); } } class beta { internal event actionhandler onevent; internal void start() { (int = 0; < 15; i++) { onevent(); thread.sleep(1000); } } } class program { static void main(string[] args) { alpha alpha = new alpha(); alpha.alphathread = new thread(new threadstart(alpha.start)); alpha.alphathread.start(); while (!alpha.alphathread.isalive) ; beta beta = new beta(); beta.onevent += new actionhandler(alpha.resume); thread betathread = new thread(new threadstart(beta.start)); betathread.start(); } } }
typically threads used allow > 1 item of work processed in parallel. i'm curious why design requires thread sleep while thread b something, wake , carry on working. why not have thread work itself?
you might benefit using .net 4's task parallel library - thread initiate asynchronous task automagically executed on separate thread, , result made available thread without need explicit inter-thread signalling (which can result in hung app if either thread or b malfunctions).
Comments
Post a Comment