gpt4 book ai didi

c# - 没有递归或无限循环的 StackOverflowException?

转载 作者:太空狗 更新时间:2023-10-29 18:28:28 25 4
gpt4 key购买 nike

背景

我有一个正在使用的 DataGridView 控件,我在下面将我的处理程序添加到 DataGridView.CellFormatting 事件中,这样可以使某些单元格中的值更人性化-可读。此事件处理程序运行良好,可以毫无问题地格式化所有值。

然而最近,我发现一个非常罕见的情况会导致一个不寻常的错误。我的 DataGridView 中项目到期日的列始终有一个 int 值。 0 表示事件永远不会到期,任何其他值都是到期日期的 UTC 时间戳。对应的 MySQL 数据库列不允许空值。当用户从一个带有截止日期的 DataGridView 行移动到另一个带有截止日期的 DataGridView 行时(此时一切看起来都很好),然后按下一个从数据库重新加载数据的按钮(不发送更新,本质上调用 DataAdapter.Fill()),程序生成一个 StackOverflowException**。

没有递归?

对我来说如此不寻常的是,我看不到递归或无限循环在哪里。我将 int cellFormatCallCount 添加为类成员,并在每次调用期间递增它,但在抛出异常时,调试器将该 int 的值显示为 1,这是我所期望的,因为我没有印象并且正在发生递归。

有人可以帮帮我吗?

如何查看堆栈跟踪?在 VS2008 中它说:{无法计算表达式,因为当前线程处于堆栈溢出状态。}

最好的问候,

罗宾逊

private int cellFormatCallCount = 0;
private void myDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
try {
// to format the cell, we will need to know its value and which column its in
string value = "";
string column = "";

// the event is sometimes called where the value property is null
if (e.Value != null) {
cellFormatCallCount++; // here is my test for recursion, this class member will increment each call

// This is the line that throws the StackOverflowException
/* ********************* */
value = e.Value.ToString();
/* ********************* */

column = actionsDataGridView.Columns[e.ColumnIndex].Name;
} else {
return; // null values cannont be formatted, so return
}

if (column == "id") {
// different code for formatting each column
} else if (column == "title") {
// ...
} else {
// ...
}
} finally {
cellFormatCallCount = 0; // after we are done with the formatting, reset our recursion counter
}
}

最佳答案

显然 e.Value.ToString() 再次调用 CellFormatting 事件。这似乎有点合乎逻辑。使用调试器应该很容易找到。

但是实际的递归可能是由其他地方引起的,比如在您省略的每列格式中。

您的递归检查不可靠,因为 Value==null 也会重置它,而且它似乎由所有列共享。让它更紧密地围绕 e.Value.ToString() :

if (e.Value != null) 
{
cellFormatCallCount++;
System.Diagnostics.Debug.Assert(cellFormatCallCount <= 1, "Recursion");
value = e.Value.ToString();
cellFormatCallCount--;
...
}

关于c# - 没有递归或无限循环的 StackOverflowException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/778963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com