winforms - About threading in .NET -
winforms - About threading in .NET -
below code sample presenting design of windows form utilize in windows ce application.
we having unresolved problems in our application, , suspect problem comes thread used here background worker (since class backgroundworker not available in windows ce).
you can see lock object used prevent multiple instances of myworker.
is right way prevent multiple instances of such "worker"? work expected? singleton worker better?
public class mainform : form { private object mylock = new object(); private bool isworkerstarted = false; private thread worker; public mainform() { } public void btn_click() { lock(mylock) { if(!isworkerstarted) { myworker worker = new myworker(); worker.startevent = new eventhandler(threadstart); worker.endevent = new eventhandler(threadstop); workerthread = new thread(worker.dowork); workerthread.start(); isworkerstarted = true; } } } public void threadstart(object sender, eventargs args) { lock(mylock) { isworkerstarted = true; // invoke delegate interact window } } public void threadstop(object sender, eventargs args) { lock(mylock) { isworkerthread = false; } this.invoke(new newformdelegate(openform)); } private void openform() { anotherwindowform awf = new anotherwindowform(); awf.show(); this.close(); } //****************** // worker class //****************** public class myworker() { public event eventhandler startevent; public void onstart() { if(startevent != null) { startevent(this, new eventargs()); } } // edit 2011-07-19 public void onend() { if(endevent != null) { endevent(this, new eventargs()); } } public void dowork() { onstart(); // work. onend(); } } }
edit 2011-07-19 here more details goal of project.
we have windows form 1 button on windows ce device. when user clicks on button, worker thread must started requesting wcf service. during execution of thread, little hourglass indicates user programme busy. when worker done (i.e. when receives "good" answer), must stops , open windows form on top of current 1 (for purpose i'm using method invoke delegate creation of new form).
the requirement user should not able run 2 workers (for illustration clicking 2 times on button). , facts sometimes, can see 2 workers making requests wcf service same device.
i not utilize lock() in case. if background worker running, main gui thread sit down on lock until other thread has finished.
i recommend instead using mutex. way can set automatically skip on section if it's locked.
so should like:
mutex mtx = new mutex(); public void btn_click() { if ( mtx.waitone(0) == true ) { //do stuff } else { //let user know can't yet? or, queue up? or, why // can user click button if can't anyway? } } you'll need mtx.release() whenever thread done doing stuff.
.net winforms locking thread-safety windows-ce
Comments
Post a Comment