在c#中读取文件导致StackOverflowException

本文关键字:StackOverflowException 文件 读取 | 更新日期: 2023-09-27 18:07:20

我目前正在做一个c# wpf项目。这些文件是以SQL语句的形式从数据库导出的数据。对于文件读取的每一行,执行语句在MySQL服务器内的数据库上执行操作。

该任务在后台工作线程中运行,报告进程,因此每次在MySQL服务器上执行一行时,它调用progress changed事件来更新进度条,以便用户知道程序已恢复到服务器的数量。

然而,当它到达某一点时,进程改变事件崩溃并产生堆栈溢出异常。下面是更新进度条的代码,这是发生stackoverflow异常的地方。

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    window.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new System.Windows.Threading.DispatcherOperationCallback(delegate
    {
        progressRestore.IsIndeterminate = false;
        progressRestore.Value = e.ProgressPercentage;
        lblRestProgress.Content = e.ProgressPercentage + "%";
        //lblRestProgressDesc.Content = "Row " + lineCount + " of " + totalRows;
        return null;
    }), null);
}

如何解决这个异常?我试过运行垃圾收集器,但我不认为这会影响堆栈,所以它没有工作,我也试过为每行读取添加一个小延迟,但这似乎也没有帮助。

在c#中读取文件导致StackOverflowException

您不应该需要window.Dispatcher.Invoke,因为BackgroundWorker已经将对ProgressChanged的调用封送回其原始SynchronizationContext。(这是假设你从UI线程开始BW…)

试着删除这个,直接设置你的值:

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
     progressRestore.IsIndeterminate = false;
     progressRestore.Value = e.ProgressPercentage;
     lblRestProgress.Content = e.ProgressPercentage + "%";
     //lblRestProgressDesc.Content = "Row " + lineCount + " of " + totalRows;
}
相关文章:
  • 没有找到相关文章