Reputation: 9
I have a button to start the Timer1, the Timer1 will print the current execution time every 100ms, but when I do something calculation, the timer1_Tick() will be paused until finished that calculation, I think the calculation bother the Timer1 so that timer1_Tick() is dropped(or blocked this thread).
In fact, the calculation is very complex, maybe take 40 seconds, I just need to show the execution time every 100ms to tell user how close to the end of this function, would you please tell me how to do this work??
double a = 0;
public Form1()
{
InitializeComponent();
timer1.Interval = 100;
}
private void timer1_Tick(object sender, EventArgs e)
{
a += 0.1;
label1.Text = a.ToString();
}
private void UserStartTimer_Click(object sender, EventArgs e)
{
a = 0.0;
timer1.Enabled = true;
}
private void UserCalcSomething_Click(object sender, EventArgs e)
{
double s = 0;
for (int i = 0; i < 100000; i++)
{
for (int j = 0; j < 10000; j++)
{
s = i + j;
}
}
}
private void UserStopTimer_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
Upvotes: 0
Views: 218
Reputation: 808
Just execute the calculation in another thread or task:
private void UserCalcSomething_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => {
double s = 0;
for (int i = 0; i < 100000; i++)
{
for (int j = 0; j < 10000; j++)
{
s = i + j;
}
}
}
}
Upvotes: 1