I have a textbox, I have using both Timer and DispatcherTimer for delay on keyup, but it not actually as my expected.
Event stil fire when Interval is finish. After 5 seconds, the Fiter event stil fire.
Here are my code:
Init variable
DispatcherTimer timerFilter;
//or
//Timer timerFilter = new Timer(5000);
Init event
InitializeComponent();
timerFiter = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timerFiter.Tick += (s, args) =>
{
Filter();
};
//or
//timerFilter.Elapsed += Filter;
When key up
Console.WriteLine("Start");
timerFilter.Start();
//or
//timerFilter.Enabled = true;
When key down
Console.WriteLine("Destroy");
timerFiter.Stop();
//or
//timerFilter.Enabled = false;
My event
private void Filter(Object source, ElapsedEventArgs e)
{
Console.WriteLine("Filter");
timerFiter.Stop();
//or
//timerFilter.Enabled = false;
}
Thanks!
There is always a key up event, so the last thing that will happen after the last key press is:
Console.WriteLine("Start");
timerFilter.Start();
To make sure that your timer stops after the results are filtered, add a Stop call to your Filter handler:
private void Filter(Object source, ElapsedEventArgs e)
{
Console.WriteLine("Filter");
timerFilter.Stop();
}
Related
I have the following issue, I'm running the timer (SetTimer), and it is supposed to, on elapsed, run the next function (OnTimedEvent).
However, when it is supposed to run, it fails with "A method was called at an unexpected time" error on the "CoreDispatch".
I have tried searching for a solution, and I think I understand what is causing it, but I'm not sure how to fix it.
Hopefully some of you can shed some light on my issue.
private void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(RandomNum(1000,2000));
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
public async void OnTimedEvent(Object source, ElapsedEventArgs e)
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
System.Diagnostics.Debug.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
}
);
}
Call DispatcherQueue.GetForCurrentThread on the UI thread to get a DispatcherQueue and then use it to enqueue dispatcher work:
readonly DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();
private void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(RandomNum(1000,2000));
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
public void OnTimedEvent(Object source, ElapsedEventArgs e)
{
dispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
{
System.Diagnostics.Debug.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
});
}
Or use a DispatcherTimer:
DispatcherTimer aTimer;
private void SetTimer()
{
aTimer = new DispatcherTimer();
aTimer.Interval = TimeSpan.FromMilliseconds(RandomNum(1000,2000));
aTimer.Tick += ATimer_Tick;
aTimer.Start();
}
private void ATimer_Tick(object sender, object e)
{
// do something on the UI thread...
}
Am implementing a System Timer on Xamarin Android and i have a problem with the elapsed event not raising a dialog box with the message "Time is up" when the countdown is Over...
I figured the problem might be not implementing the event on the User Interface thread so i need your help accomplishing that...
Here is my code for the Timer
class SecondActivity : AppCompatActivity
{
int counter = 10;
private System.Timers.Timer _timer;
private int _countSeconds;
protected override void OnCreate(Bundle savedInstanceState)
{
_timer = new System.Timers.Timer();
//Trigger event every second
_timer.Interval = 1000;
_timer.Elapsed += OnTimedEvent;
//count down 5 seconds
_timer.Enabled = true;
_countSeconds = 5;
}
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
_countSeconds--;
if (_countSeconds == 0) {
_timer.Stop();
Switch switch1 = this.FindViewById<Switch>(Resource.Id.switch2);
Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
Android.App.AlertDialog alert = dialog.Create();
alert.SetTitle("");
alert.SetMessage("Simple Alert");
alert.SetButton("OK", (c, ev) =>
{
// Ok button click task
});
switch1.Checked = false;
}
I just want the Elapsed event handler to display an alert dialog box when the variable count down equals zero, Thank You
After the first comment pointed me to a related question i found the method to implement the user thread and it now works as intended to display the alert dialog...
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
//This is how to make the Timer callback on the UI
RunOnUiThread(() =>
{
_countSeconds--;
if (_countSeconds == 0)
{
Switch switch1 = this.FindViewById<Switch>(Resource.Id.switch2);
Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
Android.App.AlertDialog alert = dialog.Create();
alert.SetTitle("Its over");
alert.SetMessage("Simple Alert");
alert.SetButton("OK", (c, ev) =>
{
// Ok button click task
});
alert.Show();
switch1.Checked = true;
}
});
}
I need to stop the event connected to the Dispatcher after the event first time tick.
Any idea how to do it.
int closeSeconds = Convert.ToInt32(utility.GetConfiguration("device", "closePopupPrinterAfterSeconds"));
var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimerCheckPopupPrinter_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, closeSeconds);
dispatcherTimer.Start();
private void dispatcherTimerCheckPopupPrinter_Tick(object sender, EventArgs e)
{
// stop the dispatcherTimer here, so this method will not fire every x seconds
System.Windows.Threading.Dispatcher displatcher = (System.Windows.Threading.Dispatcher)sender;
}
Cast the sender argument to DispatcherTimer, not Dispatcher, and call its Stop method, or set its IsEnabled property to false.
private void dispatcherTimerCheckPopupPrinter_Tick(object sender, EventArgs e)
{
var timer = (DispatcherTimer)sender; // not Dispatcher!
timer.Stop(); // or timer.IsEnabled = false;
}
I need to create a application which must have a timer control;
the timer must automatically initialize when each form is called, when the time reach 3 seconds means it must load the another form.
I have tried this:
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
if (timer1.Interval = 3000)
{
MessageBox.Show("Times up");
form2 i=new form2();
form2.show();
}
}
but I cant get the correct result....
Timers in C# work by firing events periodically. You need to attach an event handler which responds to the timer event. The MSDN documentation has a straightforward example (code snippet reproduced below).
public Timer aTimer;
public static void Main()
{
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
initialize and enable your timer and attach an event handler to Tick event.
Timer timer;
private void Form1_Load(object sender, EventArgs e)
{
timer = new Timer();
timer.Enabled = true;
timer.Interval = 3000;
timer.Tick += timer_Tick;
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Times up");
Form2 i = new Form2();
i.Show();
}
I have a timer event setup and I would like to change how often the timer event happens by reading a number from a text box. If the box is '10' and you click the update button the event would trigger every 10ms then if you changed to '100' and clicked it would happen every 100ms and so on.
When I run the program however, i can speed up the event frequency (e.g. 100ms to 10ms) but I cannot slow it down (e.g. 10ms to 100ms). Here is the piece of my code that changes the timer when I click:
private void TimerButton_Click(object sender, EventArgs e)
{
getTime = ImgTimeInterval.Text;
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = false;
timer.Interval = timerMS;
timer.Elapsed += new ElapsedEventHandler(timerEvent);
timer.AutoReset = true;
timer.Enabled = true;
}
}
public void timerEvent(object source, System.Timers.ElapsedEventArgs e)
{
label1.Text = counter.ToString();
counter = (counter + 1) % 100;
}
If anyone knows what I may be doing wrong it would be greatly appreciated.
The problem with this code is, that you create a new Timer each time you click the button. Try to create the timer outside the method. You think it's only goes faster, but instead multiple timers trigger the timerEvent
private System.Timers.Timer _timer;
private void CreateTimer()
{
_timer = new System.Timers.Timer();
_timer.Enabled = false;
_timer.Interval = 100; // default
_timer.Elapsed += new ElapsedEventHandler(timerEvent);
_timer.AutoReset = true;
_timer.Enabled = true;
}
private void TimerButton_Click(object sender, EventArgs e)
{
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
_timer.Interval = timerMS;
}
}
public void timerEvent(object source, System.Timers.ElapsedEventArgs e)
{
label1.Text = counter.ToString();
counter = (counter + 1) % 100;
}
Make sure that the CreateTimer is called in the constructor/formload. Also you can now stop the timer within another button event. With _timer.Enabled = false;
You're always creating a new timer and never stopping the old timer. When you "change" it from 100 to 10 your 100ms timer is still firing every 100 ms, so every 100ms two timers are firing at around the same time.
You need to "remember" the old timer so that you can stop it. Or, better yet, just have only one timer that you change the interval on.
private System.Timers.Timer timer = new System.Timers.Timer();
public Form1()
{
timer.Enabled = false;
timer.AutoReset = true;
timer.Elapsed += timerEvent;
}
private void TimerButton_Click(object sender, EventArgs e)
{
getTime = ImgTimeInterval.Text;
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
timer.Interval = timerMS;
timer.Enabled = true;
}
}
Well the basic problem is that you're building a new one every time. Make a private timer:
private System.Timers.Timer _timer = new System.Timers.Timer();
and then fix it up when the button is clicked:
if (isNumeric)
{
_timer.Stop();
_timer.Interval = timerMS;
_timer.Start();
}
and then in the .ctor, do this:
_timer.Elapsed += new ElapsedEventHandler(timerEvent);
Now you have a single timer that you are just modifying as the user changes the value in the text box.