I think this function should be completed by Timer.
I wrote a simple example, counting down the number.
If the entire process exceeds the time I set (5 seconds in this example), the process stops, and if I click the stop button, it also stops.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public DateTime StartDateTime { get; set; }
private void Form1_Load(object sender, EventArgs e)
{
timer1.Tick += Timer1_Tick;
}
int timeLeft = 100;
private void Timer1_Tick(object sender, EventArgs e)
{
TimeSpan duration = new TimeSpan(DateTime.Now.Ticks - StartDateTime.Ticks);
Console.WriteLine(duration.TotalSeconds);
if (duration.TotalSeconds>5)
{
timer1.Stop();
}
if (timeLeft > 0)
{
timeLeft = timeLeft - 1;
textBox1.Text = timeLeft.ToString();
}
else
{
timer1.Stop();
textBox1.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry!");
startBtn.Enabled = true;
}
}
private void startBtn_Click(object sender, EventArgs e)
{
timer1.Start();
StartDateTime = DateTime.Now;
}
private void stopBtn_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
Does this logic meet your requirements?
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.