I need to display the running time which will start with 0 - c#

I need to display the time which will start with 0 and (which will keep running in seconds)
I need to display in a game so it will show elapsed time when playing.
as shown in the screenshot:
someone told me to do this way,
Stopwatch st = new Stopwatch();
st.Start();
and display it with
Console.WriteLine(st.Elapsed);
but its not working (seconds are not running)!
it showing as:

As I understand you just need to update your display every 1 second so why not just use a Timer which will run every 1 second and increment whatever you display on the screen. (Read about Timer here: http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx)
You can find an example here:
How to set timer in C#?

If it's a game, there must be the animation (game) loop somewhere. You should put
Console.WriteLine(st.Elapsed);
there. This way it is going to refresh correctly.

Given this is a console game: Have the Elapsed time from the StopWatch stored in a TimeSpan and then just use the Thread.Sleep(); property from System.Threading(); to simulate 1 second.
Stopwatch st = new Stopwatch();
st.Start();
while (true)
{
TimeSpan ts = st.Elapsed;
string time = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
Console.Write("\r{0} ", time);
Thread.Sleep(1000);
}
PS: This is my first answer in this website and I hope I was helpful!

Related

How to measure time in millisecond precision by thread

I need to measure an event time precisely (suppose the time between two clicks). I used a timer and set the interval to "1" and a counter inside Tick event. The problem is since there are a lot of lines in my code the Tick event does not actually happen every 1ms (maybe every 8ms or more). Is there any way to use a thread and run a 1ms-timer independently in it?
//start
long start = DateTime.Now.Ticks;
//to do something
//...
//end
long end = DateTime.Now.Ticks;
long delta = end - start;
var stopWatch = Stopwatch.StartNew();
// do something
stopWatch.Stop();
Console.WriteLine(stopWatch.ElapsedMilliseconds);

how to create a countdown timer in visual studio using datetimepicker

this may sound stupid for some of you but please bear with me. I am trying to create a windows form application that has 2 datetimepicker controls. They are intended to set a time range (date selection has been disabled). After the user sets the range and hits the confirm button, the program needs to display 'A' till the limit and reached and when the timer expires, display 'B'.
This is my code right now in the click event of the confirm button
int a=0;
TimeSpan time = DateTime.Now.TimeOfDay;
TimeSpan timer = dateTimePicker2.Value - dateTimePicker1.Value;
MessageBox.Show("Timer set. Device will shutdown in " + timer);
timer = timer + time;
while (time!=timer)
{
time = DateTime.Now.TimeOfDay; ;
if(a==0)
{
MessageBox.Show("B");
a = 1;
};
};
if (a == 1)
{
MessageBox.Show("A");
a = 0;
}
My logic behind this piece of code was this: First find the difference between the two time ranges. Then add this difference to the current system time and do a while loop to check if that time has reached.If not display B. When the current system time reaches the time, display A. I have spend hours over this and cant get it working. When running this code it just displays B and never A.
I'm new to visual studio and this is my first project.
The problem is likely to be this test:
while (time!=timer)
it's highly likely that the current time will never be exactly equal to the second time you've picked. You should change this to:
while (time < endTime)
With this you'll be able to get rid of your variable a and just display "A" once the loop finishes.
Having said all this, MessageBox.Show will block the loop until you dismiss it so you really need to find some other way of indicating that you're still in the loop.

Calculating Time elapsed for ten users at the same time

I need to capture the time taken between two button press of ten users.
I am doing like this with StopWatch.
Stopwatch stopwatch1;
Stopwatch stopwatch2;
........ Like this ten stop watches.
private void Start_Action1()
{
stopwatch1 = new Stopwatch();
stopwatch1.Start();
}
private void Stop_Action1()
{
stopwatch1.Stop();
txtTimeForAction1.Text = stopwatch.Elapsed.ToString();
}
Same code for 10 StopWatches.
NOTE: All the users will do this START-STOP action continuously. I need to record time-elapsed for each cycle separately. I am using in desktop application. All the users will use the same application.
Using 10 Stopwatch is good practice?? Is there any better way than this?
You could keep track of the starting times for every user, use one stopwatch and don't stop it after the stop action is called by one user, only when they have all stopped. I don't know if it's better practice, but it is a different way to do it.
Personally, I'd give each "user" a DateTime (StartTime) and then when the event has finished (So E.g. Key_Up) You can get the Elapsed time with:
DateTime elapsedTime = DateTime.Now - StartTime.
then use elapsedTime.Seconds or .Minutes etc. and even use elpasedTime.ToString("hh:mm:ss") to get a nicely formatted string.
I see no reason why not using stop watches. But instead of defining ten stop watches you should save them in an array or in a dictionary where each StopWatch is associated with a user.

Waitable Timer, Running Every Interval?

Using C#, .NET Framework 4.0.
I have 3 TimeSpan objects set to 20 minute, 30 minutes, 45 minutes. I want to have a Timer execute only at the exact minute intervals, regardless of when any timer actually starts.
I need to have timer firing look like this (every hour):
timerA 1:00
timerB 1:00
timerA 1:20
timerB 1:30
timerA 1:40
timerC 1:45
timerA 2:00
timerB 2:00
timerA 2:20
timerB 2:30
timerA 2:40
timerC 2:45
I thought a Waitable timer would be the right move, but with the lack of simple examples out there, I guess not. What is the best way to get this functionality (I would like to avoid clock drift if possible but I'm desperate for anything right now)? I am not married to Waitable. I also understand that timerC is only going to run once an hour, which is fine since it is set to only run at the 45th minute of every hour.
Note - I am not ready to use Quartz.NET.
Thanks.
I think this will do the work for you:
static void Main(string[] args)
{
StartTimer(TimeSpan.FromMinutes(20.0), "TimerA", true);
StartTimer(TimeSpan.FromMinutes(30.0), "TimerB", true);
StartTimer(TimeSpan.FromMinutes(45.0), "TimerC", true);
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
The start timer function starts the timer and returns it (if you need the reference). The key here is that you give it the timer name and you tell it if you want to align the timer to the full hour. If you don't want to align to the full hour, then the timer will be started immediately with the specified frequency.
public static Timer StartTimer(TimeSpan frequency, string timerName, bool alignToHour)
{
if (alignToHour)
{
return new Timer(OnTimerTick, timerName, ComputeDelay(frequency), frequency);
}
else
{
return new Timer(OnTimerTick, timerName, TimeSpan.Zero, frequency);
}
}
The function that will be fired when the timer ticks.
public static void OnTimerTick(object state)
{
Console.WriteLine((string)state + " " + DateTime.Now.ToString("H:mm"));
}
This method computes the delay that would be required if the timer has to be aligned on the full hour. It only works if the frequency is less than one hour or more than one minute.
public static TimeSpan ComputeDelay(TimeSpan frequency)
{
if (frequency > TimeSpan.FromHours(1.0) ||
frequency < TimeSpan.FromMinutes(1.0))
{
throw new ArgumentException(
"The frequency cannot be more than one hour or less than one minute!");
}
return frequency - TimeSpan.FromMinutes(DateTime.Now.Minute % frequency.Minutes);
}
NOTE: in your example you run the 45 minute timer on a 1 hour frequency, yet you run the 20 and 30 minute timers on 20 and 30 minute frequencies (respectively). My code doesn't work with a 45 minute timer on a 1 hour frequency, but it does work with 20, 30 and 45 minute timers on their respective frequency. I'm not sure if your example is wrong or not, but if it's not wrong then I think you should be able to figure out how to take care of that difference from here on.
The closest I can get is to 'creep up' on the target-time, using a waitable, (sleep(), event with timeout, some threaded timer or classic 'main thread windows timer), set to half the number of milliseconds between 'now' and the target time, as calcuated from the real-time clock. If the remaining ms is greater than some limit, (say 500), recalcualate the ms remaining and wait again. When the remaining ms is lower than the limit, start looping round the real-time clock until the target is reached or exceeded, then call the timeout() method of your TimeSpan object.
You could put your TimeSpan objects in a timeout-time ordered queue so that you only need one waitable. This may be more accurate if you have cases where the TimeSpan events often happen 'simultaneously' since there is only one thread looping as the target time is neared.
Rgds,
Martin

Clock Application

I am creating a clock application in C#.Net.I have images for each digits from 0-9. I have a timer in the main page constructor which ticks every seconds
DispatcherTimer tmr = new DispatcherTimer();
tmr.Interval = TimeSpan.FromSeconds(1);
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Start();
void tmr_Tick(object sender, EventArgs e)
{
dt = DateTime.Now;
UpdateSecondsImages(dt);
}
private void UpdateSecondsImages(DateTime dt)
{
secondSource2 = dt.Second % 10;
secondDigit2.Source = digimgs[secondSource2];
if (secondSource2 == 0)
{
secondSource1 = dt.Second / 10;
secondDigit1.Source = digimgs[secondSource1];
}
if (secondSource1 == 0)
{
UpdateMinuteImages(dt);
}
}
But the problem I am facing now is this code may skip a second for a minute.Please suggest alternate way to make this smooth from a performance point of view.
Simple. When you set a timer to go off every second you are saying, "please sleep for at least 1 second before waking up and notifying me". In reality, you could be sleeping for much longer. Also, different timing APIs have clock drift relative to each other. The clock that timers are based on may not be the same clock that the DateTime.Now is based on.
Think of it like this - let's say you are actually be waking up once every 1.02 seconds.
Hence, every 50 seconds, you'll skip a beat in rendering. For example you'll go from waking up at "49.98" (rendered as "49") and then your next interval you are woken up at "51.00".
The simple workaround is to sleep for sometime less than 1 second. In your case, I suggest sleeping between 500-750 milliseconds instead of a full second. You can simply re-render the same time again in the case where you wakeup within the same second interval. Or as a trivial optimization, just do nothing when you've already woken up an the second count hasn't changed since previous time.
try saying:
tmr.Interval = TimeSpan.FromMilliSeconds(500);
If it's okay to show clock only when they're visible, I'd rather suggest to use CompositionTarget.Render event handler. Get current time in it and update the UI appropriately. This will not only eliminate the error but will let you render milliseconds as well :).
I highly doubt this approach impacts performance (cos() and sin() are damn fast in our days). But even if it will (you are rendering thousands of clocks), you can update UI not on every frame.
Hope this helps.
Yesterday we launched a contest with Ball Watch USA to create watches in Silverlight. I recommend using a Storyboard to rotate the second hand 360 degrees over 1 minute and set the storyboard to repeat forever. Here are some links:
The Contest
A video describing the task
The animation XAML in SL1
Updating the code to SL2

Categories

Resources