c# - Stopwatch application starts but won't stop -


for reason able start stopwatch, when try , click stop button, nothing happens.

i have background in java programming assigned project make program in language didn't know picked c#. have knowledge c# appreciate if can me out problem.

using system; using gtk; using system.threading; using system.diagnostics; using system.timers;  public partial class mainwindow: gtk.window {     stopwatch stopwatch = new stopwatch();     system.timers.timer timer  = new system.timers.timer();     bool stopclicked = false;      public mainwindow () : base (gtk.windowtype.toplevel)     {         build ();     }      protected void ondeleteevent (object sender, deleteeventargs a)     {         gtk.application.quit ();         a.retval = true;     }      protected void onstartbuttonclicked (object sender, eventargs e)     {         thread thread1 = new thread(new threadstart(thread1));         thread1.start ();         stopwatch.start ();         console.writeline ("stopwatch started");          timer.elapsed += new elapsedeventhandler (timertick);         timer.interval = 100;         timer.enabled = true;         timer.start ();         console.writeline ("timer started");     }      protected void onstopbuttonclicked (object sender, eventargs e)     {         stopclicked = true;     }      void timertick(object sender, eventargs e)     {         timelabel.text = stopwatch.elapsed.tostring ();         system.windows.forms.application.doevents ();     }      void thread1()     {         if(stopclicked)         {             timelabel.text = stopwatch.elapsed.tostring ();             timer.stop ();             timer.enabled = false;             timer.dispose ();             console.writeline ("timer stopped");             stopwatch.stop ();             console.writeline ("stopwatch stopped");         }      }  } 

your thread not doing anything. thread method runs once. need @ least loop check whether stopclicked clicked @ point.

void thread1() {     while (!stopclicked)     {         thread.sleep(100);     }      // rest of code finish timer. } 

actually not quite understand why need thread @ all. stop timer when stop button clicked. no need separate thread here. , causes kinds of problems.

also there's no need do

system.windows.forms.application.doevents(); 

the ui update when timer method left, anyway. , it's not practise. also, system.timers.timer called in separate thread, should getting cross-thread-exception here.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -