For some reason I am able to start the stopwatch, but when I try and click the stop button, nothing happens.
I have some background in java programming but I was assigned a project to make a program in a language I didn't know so I picked C#. I have some knowledge about C# but would greatly appreciate if someone can help me out with this 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");
}
}
}
It is because Thread1 is running just once, you should use a busy wait loop to do this something like
but you can move the whole logic to
OnStopButtonClicked
and there is no need to use threads anymore