i want timer to run a counter from 0 to 3. i added the timer from the toolbox in visual basics 2008 (instead of creating an object and using properties) you can see the Timer at the bottom of the winform..
int timerCounter;
private void animationTimer_Tick(object sender, EventArgs e)
{
//timer should go 0,1,2,3..and then reset
while (true)
{
timerCounter++;
if (timerCounter > 3)
{
timerCounter = 0;
}
game.Twinkle();
//screen gets repainted.
Refresh();
}
}
will the timer work?
(i enabled it and set it to 33 milliseconds)
Set the timer's interval to 1000 (which is 1000ms or 1 second). Then when you enable it, it'll go on and on and on, firing the timer1_tick event every time it goes through the interval.
Here's an example on how to do it:
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count++;
if (count == 3)
{
//Do something here, because it's the third toll of the bell.
//But also reset the counter after you're done.
count = 0;
}
}
Don't forget to .Enable the timer!
Related
I am starting a timer and I want the method to wait until some time passed. I have searched in other similar questions but cannot find a clear answer.
Why is does the following code freeze the app?
elapsed time starts at 0 and intervall is 1000 (1sec)
private void timer2_Tick(object sender, EventArgs e)
{
elapsedtime2++;
}
//this is inside my method
timer2.Start();
while (elapsedtime2 < 3)
{
}
timer2.Stop();
The easiest way to pause execution for a second is:
Thread.Sleep(1000);
If you're familiar with async/await, the async equivalent is:
await Task.Delay(1000);
You can use events to get the desired behaviour:
private int elapsedtime2 = 0;
private ManualResetEventSlim mre = new ManualResetEventSlim();
private void timer2_Tick(object sender, EventArgs e)
{
elapsedtime2++;
if(elapsedtime2 >= 3)
{
mre.Set();
}
}
If your elapsed time variable has the expected value, you can set the event.
mre.Reset();
timer2.Start();
mre.Wait();
timer2.Stop();
Before you start the timer, you unset the event. After you started your timer, you wait until the event is set.
I have a little problem. There is something like chess timer. When i press button, current timer stops and second starts, but after 1 second. How can i start second one immediately?
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1 {
public partial class Form1 : Form {
byte sec1;
byte sec2;
public Form1() {
InitializeComponent();
sec1 = 0;
sec2 = 0;
}
private void button1_Click(object sender , EventArgs e) {
timer1.Start();
timer2.Stop();
}
private void button2_Click(object sender , EventArgs e) {
timer2.Start();
timer1.Stop();
}
private void timer1_Tick(object sender , EventArgs e) {
label1.Text = sec1.ToString();
sec1++;
}
private void timer2_Tick(object sender , EventArgs e) {
label2.Text = sec2.ToString();
sec2++;
}
}
}
Edit
I know your question is "how to start the timers immediately", but in your code they are starting immediately. When you call start the timer starts. I believe the effect you are seeing is related to the delay associated with the tick event, which from the description I am assuming is set to a 1 second interval. Since you have said that you are trying to simulate something similar to a chess timer (although in your case counting up as opposed to down), then using something like a stop watch which can start, stop and show elapsed time would be a closer model. Since there is a Stopwatch class that provides exactly this behavior, I think it would be easier to implement it using two of those and just have a single background thread that updates the UI as frequently as needed. You could even add an update call into each button push to ensure the text boxes are up to date.
===============================
Maybe instead of the timers you should use two instances of the Stopwatch class. This will remove the need for your two variables that you are using to keep track of the seconds as the Stopwatch class will be holding the elapsed time for each counter.
Then in your button methods you could just do this:
private Stopwatch sw1 = new Stopwatch();
private Stopwatch sw2 = new Stopwatch();
private void button1_Click(object sender , EventArgs e) {
sw1.Start();
sw2.Stop();
}
private void button2_Click(object sender , EventArgs e) {
sw2.Start();
sw1.Stop();
}
And then you can use a Background worker or some other background thread that runs and updates your text boxes with the elapsed time from the timers you just need to grab the elapsed time.
// This will give you the total number of seconds elapsed.
var timer1Seconds = Math.Floor(sw1.Elapsed.TotalSeconds);
Here is an example of how you can make this update the UI:
private bool _stop = false;
public Form1()
{
InitializeComponent();
Task.Run(() =>
{
while(!_stop)
{
UpdateElapsedTimes();
Thread.Sleep(1000);
}
}
}
private void UpdateElapsedTimes()
{
if (InvokeRequired)
{
Invoke(UpdateElapsedTimes());
return;
}
label1.Text = Math.Floor(sw1.Elapsed.TotalSeconds).ToString();
label2.Text = Math.Floor(sw2.Elapsed.TotalSeconds).ToString();
}
Note - in a production program I would not use a boolean as my loop checker, you would use an event handle, and probably a couple of event handles if you wanted to allow pausing the updates, this is just to show an idea of how to do it. You could invoke directly from the thread method and drop the InvokeRequired check, but I added that for additional safety and since it was there I skipped it in the loop.
The timer does start immediately. The problem is that you are not reporting fractions of seconds, so the display will show 0 until a full second has elapsed, which is accurate, technically.
If you want to show 1 immediately, just initialize your variables that way.
public Form1() {
InitializeComponent();
sec1 = 1;
sec2 = 1;
}
I made a sample project. Where every 10 second it do some function. But when I try to show a timer tick in label it always stuck, and jump to certain second (eg: stuck at 9s and suddenly jump to 12s). What i want to ask,
Is my function run properly ?
Is my tick, skipped a few ms ? (it will overlap with my function)
How do I run it as a thread ?
My code
private void button2_Click(object sender, EventArgs e)
{
timer1.Start();
}
int x = 0;
private void timer1_Tick(object sender, EventArgs e)
{
x += 1;
label1.Text = x.ToString();
if (x % 10 == 0)
{
addpoint();
//MessageBox.Show("success");
}
}
how to keep my label1.text keep updating, while do addpoint() function
Note:
I have set timer1 interval = 1000
update
i test it with this.
public void addpoint()
{
string x = #"c:\test\a.txt";
string text = "haiaiaia";
using (FileStream fs = new FileStream(x, FileMode.Create))
{
Byte[] xx = Encoding.ASCII.GetBytes(text);
fs.Write(xx, 0, xx.Length);
}
Messagebox.show("Created !");
}
It looks like your using a Windows.Forms.Timer which is executed on the main thread. The advantage is that you don't need to call Invoke, the disadvantage is that addpoint is also executed on the main thread and hence blocks your GUI from update, when in the mean time the next tick events are fired.
You can verify it be replacing the call of addpoint with Thread.Sleep(3000) and you will experience the same behaviour.
What you could do is to try and run the method on another thread:
private void timer1_Tick(object sender, EventArgs e)
{
x += 1;
label1.Text = x.ToString();
if (x % 10 == 0)
{
Thread t = new Thread(addpoint);
t.Start();
}
}
This should avoid the blocking of the GUI.
Disclaimer:
It is important to know what you actually do in addpoint, because this solution might lead to race condition and wrong functioning of the method. For example if you are using class variables in it, and if the possibility exists that a second thread can be started while the first has not finished yet! Be aware.
I need to store the piano duration with Ticks as so then make the music note show according to that duration (Music players would know).
I'm using an interval of 100, but for some testing I used it at 1000.
The problem is this. When I'm invoking the method (I'm taking the 1000 millisecond interval one) the timer starts.. if I DO NOT manage to get the 1000 milliseconds it shows Duration 0: but then if I do for example 2 seconds, it shows 3 seconds, if I try to press it for another second (a different key) it would show 4 seconds instead of 1.
It's like it keeps on recurring. Same happened with the 100 interval one. It went mad. sometimes 40 sometimes 23 and so on. Any idea how to fix (resetting the timer)
N.B I'm using System.Windows.Forms.Timer as library
part of a method which invokes the methods further below
for (int i = 0; i < 15; i++)
{
WhiteKey wk = new WhiteKey(wKeys[i], wPos[i]-35,0); //create a new white Key with [i] Pitch, at that x position and at y =0 position
wk.MouseDown += onRightClick; //holds the Duration on Right Click
wk.MouseUp += onMouseUp;
wk.Click += new EventHandler(KeyClick); //Go to KeyClick Method whenever a key is pressed
this.panel1.Controls.Add(wk); //Give it control (to play and edit)
}
Methods controlling the time
private void onRightClick(object sender, MouseEventArgs e)
{
wk = sender as WhiteKey;
duration = 0;
t1.Enabled = true;
t1.Tick += timeTick;
t1.Interval = 100;
}
private void timeTick(object sender, EventArgs e)
{
duration++;
}
private void onMouseUp (object sender, MouseEventArgs e)
{
t1.Enabled = false;
String time = "Key: " + pitch + "\nDuration: " +duration ; //Test purposes to see if timer works
MessageBox.Show(time);
}
You are trying to measure time, don't use Timer, use Stopwatch.
You can find C# Stopwatch Exmples at dotnetpearls.com.
In abstract this is what you would want to do is something like this:
private void onRightClick(object sender, MouseEventArgs e)
{
stopwatch.Reset();
stopwatch.Start();
}
private void onMouseUp (object sender, MouseEventArgs e)
{
stopwatch.Stop();
String msg = "Duration in seconds: " + (stopwatch.ElapsedMilliseconds / 1000.0).ToString("0.00");
MessageBox.Show(msg);
}
Note: you may want to change the units or the string format.
Notes on using timer:
1) System.Windows.Forms.Timer uses the message loop of your window, this means that it may get delayed because the window is busy handling other events (such as click). For a better behaviour use System.Threading.Timer.
2) If using System.Windows.Forms.Timer don't set the Tick event handler each click. The event handler will execute once for each time you add it.
That is:
private void onRightClick(object sender, MouseEventArgs e)
{
wk = sender as WhiteKey;
duration = 0;
t1.Enabled = true;
//t1.Tick += timeTick; you should add this only once not each click
t1.Interval = 100;
}
3) If you use System.Threading.Timer you may want to make the variable duration volatile.
t1.Tick += timeTick;
By the way in your code sample you subscribe to the 'Tick' timer event each time on Right mouse click.
So if you click 2 times the
private void timeTick(object sender, EventArgs e)
method will be called twice, and 'duration++' will be executed twice. Your event subscription code should be executed only once for the timer.
P.S. If you need to measure duration, Timer is not the best way to do it.
I have a timer with 10 seconds interval and on timer_Tick event I do some stuff which usually needs about a second, but sometimes it needs More than 90 seconds. How will it act? Is this event synchronous to wait for the eventhandler to finish executing? I tested but still I need an answer...
private void checkTimer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Test");
for (int i = 0; i < 2000000000; i++)
{
}
MessageBox.Show("Test");
}
when i test it after first tick MessageBox is shown. I don't click OK and wait for another tick. And another MessageBox is shown on the seconds tick and so on...
in MSDN Documentation I read that it is synchronous... Any Idea?
I solved it by adding timer disabling at the beginning of tick event and enabling at the end of tick event. like this
private void checkTimer_Tick(object sender, EventArgs e)
{
checkTimer.Enabled = false;
MessageBox.Show("Test");
for (int i = 0; i < 2000000000; i++)
{
}
MessageBox.Show("Test");
checkTimer.Enabled = true;
}
I see nothing in the System.Windows.Timers Documentation that you linked to that mentions it being synchronized. If you want each Tick event to wait to the previous Tick Event has finished. Stop the Timer at the start of your handler and restart in after your work is done. That is what the MSDN documentation shows.