I have a C# .NET console application that sends an email using SmtpClient
.
I am experiences the following behavior in the code shown below:
Why does my break point jump around?
What does that message mean?
Is there anything wrong with my code?
(Here's another similar question on Stackoverflow. Probably the same thing, but it's ASP.NET)
Per Hans Passants's tip follows.
This version still permits race condition: Toggle Timer.AutoReset
property in my timer's event handler to avoid re-entrancy while code is running.
private void OnTimerElapsed(object source, ElapsedEventArgs e)
{
timer.AutoReset = false; // prevent another Elapsed event
MyClass.SendMail(smtpServer, account, password); // do stuff
timer.AutoReset = true; // allow another Elapsed event
}
Final version: Initialize the timer with AutoReset
already set to false, then call Timer.Start()
again at the end of your Elapsed event handler.
public void Start()
{
timer = new Timer(checkInterval);
timer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
timer.AutoReset = false; // prevent race condition
timer.Start();
}
private void OnTimerElapsed(object source, ElapsedEventArgs e)
{
bool exceptionIsNasty = false;
try {
MyClass.SendMail(smtpServer, account, password); // do stuff
}
catch (Exception ex) {
// Log exception, set exceptionIsNasty to true if the mailing should be stopped
//...
}
finally {
if (!exceptionIsNasty) timer.Start(); // allow another Elapsed event
}
}
Select a thread. Right-click the thread. Select "Kill thread" from the context menu.
To display the Threads window in break mode or run mode While Visual Studio is in debug mode, select the Debug menu, point to Windows, and then select Threads.
You've got more than one thread executing the same method and they all hit the same breakpoint. When you continue stepping, the debugger cannot accurately guess anymore which thread it should show the state for. So you just get a warning that you are now looking at the state of a different thread. The local variable values are liable to be different. As is the execution location of course, the reason the highlight changes.
Clearly this can make debugging more difficult. You want to avoid this if you are still getting bugs out of the code, start just one thread. Beyond that, a temporary workaround is to use Debug + Windows + Threads, right-click one of the threads and select Freeze. Don't forget to unfreeze again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With