Reputation: 25
lets say i have 2 Windows ( loginWindow and MainWindow ). When a certain time runs out(lets say 30 seconds) i want that my Program automatically logs of ( open loginWindow ) again. I tried to code a global stopwatch that i can reset from where ever i want to in my Programm so i can open loginWindow after the time runs out. This is what i got: (also im very new into WPF)
public static Stopwatch stopwatch = new Stopwatch();
public static long timeSpan;
public static void startStopwatch()
{
stopwatch.Start();
Thread.Sleep(10000);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
timeSpan = stopwatch.ElapsedMilliseconds / 1000;
}
public static void restartStopwatch()
{
stopwatch.Stop();
startStopwatch();
}
public Page1()
{
InitializeComponent();
GlobalClass.startStopwatch();
if(GlobalClass.timeSpan == 10)
{
MessageBox.Show("Stopwatch reached end"); //also jump back to loginWindow
}
}
so this doesnt work but i dont know why. my Question is: before i go more into Stopwatch should i solve this Problem with Stopwatch or use a different way to achieve what i want. also why is this not working:(.
thanks in Advance <3
Upvotes: 0
Views: 373
Reputation: 64
You can implement a timer as a Singelton and register the navigation handler (or your navigation concept) to the TickEvent. The event is triggered when the time you set has expired and you can return to the logon screen.
You can now start/stop/reset from different locations.
public class GlobalTimer : Timer
{
private GlobalTimer instance;
public GlobalTimer Instance => instance ?? (instance = new GlobalTimer());
private GlobalTimer()
{
}
}
Edit: A StopWatch, as the name suggests, is a class that measures a time span. What you want to have is more of an alarm clock that informs you when a certain time has elapsed.
Your program does not work because you are waiting in the UI creation. This means that the UI is not yet drawn and you tell the thread who is drawing
wait 10 seconds and then draw the previous one again. Page1 is therefore not displayed.
Therefore never Thread.wait(x)
in a UI thread (your UI freezes when the thread is not working (sleeping)).
Here is a Link to the Timer Class for more information how an Timer work: https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
Edit 2: As Clemens said, the DispatcherTimer is the better option for a UI application because events are processed with the UI thread. If you want to use the "normal" timer, you may have to call UI elements(variables/Methoen/etc.) using a dispatcher. Otherwise data will be managed in different threads which does not work.
See the answer/more infos here: WPF - Threads and change variable
Upvotes: 1