Timer.Tick event handler not getting event Timer_Tick in Timer - c#

Hi I am working with Windows.Forms.Timer with Web Application . I create Timer.Tick event handler to handle Timer_Tick but I am not successfull. I don't get any error but I can not get result even. Here is my code
System.Windows.Forms.Timer StopWatchTimer = new System.Windows.Forms.Timer();
Stopwatch sw = new Stopwatch();
public void StopwatchStartBtn_Click(object sender, ImageClickEventArgs e)
{
StopWatchTimer.Enabled = true;
StopWatchTimer.Interval = 1;
StopWatchTimer.Start();
this.StopWatchTimer.Tick += new EventHandler(StopWatchTimer1_Tick);
sw.Start();
}
protected void StopWatchStopBtn_Click(object sender, ImageClickEventArgs e)
{
StopWatchTimer.Stop();
sw.Reset();
StopWatchLbl.Text = "00:00:00:000";
}
public void StopWatchTimer1_Tick(object sender,EventArgs e)
{
TimeSpan elapsed = sw.Elapsed;
StopWatchLbl.Text = string.Format("{0:00}:{1:00}:{2:00}:{3:00}",
Math.Floor(elapsed.TotalHours),
elapsed.Minutes,
elapsed.Seconds,
elapsed.Milliseconds);
}

From the MSDN documentation for Windows Forms Timer (emphasis mine):
Implements a timer that raises an event at user-defined intervals. This timer is optimized for use in Windows Forms applications and must be used in a window.
This timer will not work in a web application. You'll need to use another class, like System.Timers.Timer. This has it's own pitfalls, however.

Did you try defining the Tick event prior to starting the timer?
this.StopWatchTimer.Tick += new EventHandler(StopWatchTimer1_Tick);
StopWatchTimer.Start();

public partial class TestFrom : Form
{
private Thread threadP;
private System.Windows.Forms.Timer Timer = new System.Windows.Forms.Timer();
private string str;
public TestFrom()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Timer.Interval =100;
Timer.Tick += new EventHandler(TimeBussiness);
Timer.Enabled = true;
Timer.Start();
Timer.Tag = "Start";
}
void TimeBussiness(object sender, EventArgs e)
{
if (threadP.ThreadState == ThreadState.Running)
{
Timer.Stop();
Timer.Tag = "Stop";
}
else
{
//do my bussiness1;
}
}
private void button3_Click(object sender, EventArgs e)
{
ThreadStart threadStart = new ThreadStart(Salver);
threadP= new Thread(threadStart);
threadP.Start();
}
private void Salver()
{
while (Timer.Tag == "Stop")
{
}
//do my bussiness2;
Timer.Start();
Timer.Tag = "Start";
}
}

Related

Timer tick events does not fire in a backgroundworker do_work

I have a background worker which i am using to perform some task. Its working as expected. However, i have a timer that i want to add and make it start the bw and counting like 10 seconds after page load. I put my timer.Interval to 10000. the timer has a tick events as below
private DateTime dateETA;
private void TimerEventHandler(object sender, EventArgs e)
{
while (bw.CancellationPending ==false)
{
if (timerPro.Enabled == true)
{
dateETA = Convert.ToDateTime("1/1/0001 00:00:00");
dateETA = dateETA.AddMilliseconds(timerPro.Interval);
lblETA.Visible = true;
lblETA.Text = "Elapsed Time : " + Convert.ToString(dateETA.TimeOfDay);
// SetText("timer");
}
}
}
My background worker async is on the page contructor method and therefore run on load. just like below
if (bw.IsBusy != true)
{
this.btnPause.Enabled = true;
this.btnStop.Enabled = true;
btnStart.Enabled = false;
// timerPro.Start();
bw.RunWorkerAsync();
}
I wanted to start the timer together with my task therefore i put it before my bw.async . Then i realized the timer tick events does not fire when put before or within the dowork method of the background worker. I thought may be the bw thread is blocking the event from firing then i use an invoke method like below within the dowork in my attempt to start the timer or trigger the tick event of the timer.
this.Invoke((MethodInvoker)(() => { timerPro.Enabled = true; }));
It still does not fire. I am confused and any help or alternative would be appreciated.
I think you just want a running elapsed timer while the backgroundworker does its thing?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private System.Diagnostics.Stopwatch SW = new System.Diagnostics.Stopwatch();
private void Form1_Load(object sender, EventArgs e)
{
timerPro.Interval = 1000;
timerPro.Tick +=new EventHandler(TimerEventHandler);
SW.Start();
timerPro.Start();
bw.RunWorkerAsync();
}
private void TimerEventHandler(object sender, EventArgs e)
{
lblETA.Visible = true;
TimeSpan TS = SW.Elapsed;
string elapsed = String.Format("{0}:{1}:{2}", TS.Hours.ToString("00"), TS.Minutes.ToString("00"), TS.Seconds.ToString("00"));
lblETA.Text = "Elapsed Time : " + elapsed;
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
// ... do some work ...
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
timerPro.Stop();
}
}

changing text of button with timeout in c#

How can I change the text of button with timeout? I tried out with the following code but it is not working.
private void button1_Click(object sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
if (button1.Text == "Start")
{
//do something
button1.Text = "stop"
if (sw.ElapsedMilliseconds > 5000)
{
button1.Text = "Start";
}
}
How can I correct my code?
You need to use Timer instead:
Timer t = new Timer(5000); // Set up the timer to trigger on 5 seconds
t.SynchronizingObject = this; // Set the timer event to run on the same thread as the current class, i.e. the UI
t.AutoReset = false; // Only execute the event once
t.Elapsed += new ElapsedEventHandler(t_Elapsed); // Add an event handler to the timer
t.Enabled = true; // Starts the timer
// Once 5 seconds has elapsed, your method will be called
void t_Elapsed(object sender, ElapsedEventArgs e)
{
// The Timer class automatically runs this on the UI thread
button1.Text = "Start";
}
Stopwatch is only for measuring how much time has passed since you called Start().
If you're using C# 5
private async void button1_Click(object sender, EventArgs e)
{
button1.Text = "Stop";
await Task.Delay(5000);
button1.Text = "Start";
}
You could use a timer. In this example the text of the button changes to "Stop" after 5 seconds.
private Timer timer = new Timer();
private void button1_Click(object sender, EventArgs e)
{
timer.Interval = 5000; // interval length
timer.Tick += TimerOnTick;
timer.Enabled = true; // activate timer
button1.Text = "Start";
}
private void TimerOnTick(object sender, EventArgs eventArgs)
{
timer.Enabled = false; // deactivate timer
button1.Text = "Stop";
}
I think you can reach your goal by using Timer
Example of using Timer
public partial class FormWithTimer : Form
{
Timer timer = new Timer();
public FormWithTimer()
{
InitializeComponent();
// Everytime timer ticks, timer_Tick will be called
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = (1000) * (1); // Timer will tick every second
timer.Enabled = true; // Enable the timer
}
// .......
showForm() // declaration
{
timer.start();
// .......
timer.stop();
}
void timer_Tick(object sender, EventArgs e)
{
//hide form...through visibility
}
}
Use this instead of Stopwatch:
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "stop"
aTimer = new System.Timers.Timer(5000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
button1.Text = "Start";
var atim = source as Timer;
if (atim != null)
atim.Elapsed -= OnTimedEvent;
}

dll: timer not firing

I have a dll that has a timer control in it, inside I have a message box. The timer has been enabled and the interval has been set to 100 seconds, but for some reason it's not firing. I added button to check if it's enabled, and timer1.enabled property is set to true, but it doesn't fire even once. Any ideas what could be wrong? Thanks!
Dll Code:
private void timer1_Tick(object sender, EventArgs e)
{
MessageBox.Show("Test");
}
This is how I call the dll form:
M.ModuleInterface module = Activator.CreateInstance(t) as M.ModuleInterface;
Thread t = new Thread(module.showForm);
t.Start();
showForm Method:
void M.ModuleInterface.showForm()
{
log("GUI::Initialized()");
frm.ShowDialog();
}
i believe, judging by your words alone, that you simply forgot to register to the time.
do:
public Form1()
{
InitializeComponent();
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
}
private void timer1_Tick(object sender, EventArgs e)
{
// Your code here
}
this little example works just fine:
private System.Windows.Forms.Timer timer1;
public Form1()
{
InitializeComponent();
timer1 = new System.Windows.Forms.Timer();
timer1.Interval = 100;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
timer1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
// timer is triggered. code here is called
}

Timer won't tick

I have a Windows.Forms.Timer in my code, that I am executing 3 times. However, the timer isn't calling the tick function at all.
private int count = 3;
private timer;
void Loopy(int times)
{
count = times;
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
count--;
if (count == 0) timer.Stop();
else
{
// Do something here
}
}
Loopy() is being called from other places in the code.
Try using System.Timers instead of Windows.Forms.Timer
void Loopy(int times)
{
count = times;
timer = new Timer(1000);
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
throw new NotImplementedException();
}
If the method Loopy() is called in a thread that is not the main UI thread, then the timer won't tick.
If you want to call this method from anywhere in the code then you need to check the InvokeRequired property. So your code should look like (assuming that the code is in a form):
private void Loopy(int times)
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
Loopy(times);
});
}
else
{
count = times;
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
}
I am not sure what you are doing wrong it looks correct, This code works: See how it compares to yours.
public partial class Form1 : Form
{
private int count = 3;
private Timer timer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Loopy(count);
}
void Loopy(int times)
{
count = times;
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
count--;
if (count == 0) timer.Stop();
else
{
//
}
}
}
Here's an Rx ticker that works:
Observable.Interval(TimeSpan.FromSeconds(1))
.Take(3)
.Subscribe(x=>Console.WriteLine("tick"));
Of course, you can subscribe something more useful in your program.
you may have started the timer from another thread, so try invoking it from the correct thread.
for example, instead of:
timerX.start();
Use:
Invoke((MethodInvoker)delegate { timerX.Start(); });
Check if your timer in properties is enabled.
Mine was false and after setting to true it worked.
If you are using Windows.Forms.Timer then should use something like following.
//Declare Timer
private Timer _timer= new Timer();
void Loopy(int _time)
{
_timer.Interval = _time;
_timer.Enabled = true;
_timer.Tick += new EventHandler(timer_Elapsed);
_timer.Start();
}
void timer_Elapsed(object sender, EventArgs e)
{
//Do your stuffs here
}
If you use some delays smaller than the interval inside the timer, the system.timer will execute other thread and you have to deal with a double thread running at the same time. Apply an InvokeRequired to control the flow.

Why the DispatcherTimer delegate on work in WinRT?

the code below works in Windows Phone 7
private void ShowTime()
{
txtTime.Text = get24hour();
//display the Date and week.
DateTime nowtime = DateTime.Now;
txtWeek.Text = nowtime.DayOfWeek.ToString();
txtDate.Text = nowtime.Date.ToString("MM/dd");
//create timer to fresh to time
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMinutes(1);
timer.Tick += timer_Ticker;
timer.Start();
}
private void timer_Ticker(object sender, EventArgs e)
{
txtTime.Text = get24hour();
}
private string get24hour()
{
return DateTime.Now.ToString("HH:mm");
}
but error in WinRT (Metro)
error part:
timer.Tick += timer_Ticker;
error message:
No overload for 'timer_Ticker' matches delegate 'System.EventHandler<object>'
what I do
I try to change the code to
private void timer_Ticker()
{
txtTime.Text = get24hour();
}
result
but it is not work again, why and how to solve it? :(
timer.Tick += new EventHandler<object>(timer_Tick);
private void timer_Tick(object sender, object e)
{
}
Refer to this link
I read the msdn and change the delegate method to below and it works:
private void timer_Ticker(object sender, object e)
{
txtTime.Text = get24hour();
}

Categories