问题
I have a winform application. Every few seconds I check some log files, read in any new data and insert any new data into a DB.
When I run the application for around an hour 1/2, I get a StackOverflowException
. There was no new data in the log files for that entire period, so nothing new was added to the DB.
The code errored here...
if (pictureBox == null)
{
continue;
}
if (pictureBox.InvokeRequired)
{
var toolTip = new ToolTip();
GameServer tempGameFile = gameServer;
pictureBox.Invoke(new MethodInvoker(
() => toolTip.SetToolTip(pictureBox,
string.Format(
"{0} : Last Checked: {1}; Last Updated: {2}",
tempGameFile.Name,
tempGameFile.CheckedOn.ToLongTimeString(),
tempGameFile.UpdatedOn.HasValue
?
tempGameFile.UpdatedOn.Value.ToLongTimeString()
: "-No Date Set-"))));
}
pictureBox.Image = Resources.RedButton;
and the pictureBox.Invoke(..)
is throwing that error.
So .. i'm not sure how I can bebug this to figure out what is going on? Any suggestions?
UPDATE
Trying the suggestions of Dmitry I've started an ANTS profiler memory profile .. and having a quick look at things .. there seems to be a lot of instances of ToolTip controls.
This is a class list summary after 20 mins.

Lots of EventHandlers (am I not releasing something?)
And there's a few ToolTips also...
Here is a screenshot of all the instances and here is a screenshot of a single ToolTip control graph/map .. which I don't know how to read blush
回答1:
You have 2 potential issues with your code:
var toolTip = new ToolTip();
and
pictureBox.Image = Resources.RedButton;
are both called on non-UI thread. I have to marshal this code to UI thread using Control.Invoke. If fixing this does not help, look at my answer on how to debug StackOverflowException in windows service.
UPDATE: try this code. Note that every statement that references any UI control needs to be marshaled using Control.Invoke:
if (pictureBox == null || !pictureBox.IsHandleCreated) {
continue;
}
Action setTooltipAndImage = () => {
var toolTip = new ToolTip();
GameServer tempGameFile = gameServer;
toolTip.SetToolTip(pictureBox, string.Format(...));
pictureBox.Image = Resources.RedButton;
};
if (pictureBox.InvokeRequired) {
pictureBox.Invoke(setTooltipAndImage);
} else {
setTooltipAndImage();
}
It might worth reading Manipulating Controls from Threads.
回答2:
If you can run your application in debug mode, when you hit the StackOverflowException and the application breaks into visual studio, open up the call stack window (Debug -> Windows -> Call Stack) and take a look at what is causing your code to throw the exception.
来源:https://stackoverflow.com/questions/7225959/how-can-i-debug-this-stackoverflowexception-in-my-winform-application