Reputation: 13
I have been trying to make a Windows application, in which when I receive a message 'some_string' (from a server) I need to change the color of label (sys2lbl in code) to green and it shall stay green for 15 seconds and then turn red. However, for example, during the 5th second if I receive the message 'some_string' again, then the label should stay green for 15 seconds more i.e. 5+15 = 20 in total.
I'm using Task.Run(), as per my understanding, this task shall be restarted somehow when I receive the string 'some_string' within these 15 seconds.
Note: This Task runs perfectly if I receive 'some_string' after 15 seconds.
Does anyone know how to solve this?
Task.Run(() =>
{
if (x.ApplicationMessage.Topic == "some_string")
{
sys2lbl.BackColor = Color.Green;
Thread.Sleep(15000);
sys2lbl.BackColor = Color.Red;
}
});
Upvotes: 0
Views: 383
Reputation: 112632
You can use the Timer
from the System.Windows.Forms
namespace. In your form declare
private readonly Timer _timer = new Timer();
Initialize it like this
public Form1()
{
InitializeComponent();
_timer.Interval = 15000; // Milliseconds
_timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
_timer.Stop();
sys2lbl.BackColor = Color.Red;
}
Then you can start or restart the timer with
private void RestartTimer()
{
_timer.Stop();
sys2lbl.BackColor = Color.Green;
_timer.Start();
}
I often use this technique to delay the execution of a query. As an example, let us assume that we have a data grid and a textbox used to filter the data in the grid. In the TextChanged
event of the textbox we start the timer with a short delay (e.g., 200 ms). In Timer_Tick
we stop the timer and re-query the data.
The advantage is that the data is re-queried without the user having to hit Enter or to click a button. But on the other hand, the data is not re-queried after every keystroke, which could be problematic if the query execution is slow.
If the user types the next character before the timer delay elapses, the timer is restarted. If the query is executed while entering the filter because the user is typing slowly, the next keystrokes will be accumulated and then inserted in the textbox all at once when the data update is completed. This reduces the number of re-queries and makes the UI more responsive.
Note that in Windows Forms, events are executed strictly sequentially. A new event will never interrupt a method (which can be an event handler) running on the UI thread. Therefore, you will never have multithreading issues with a timer.
Upvotes: 2