c# - 检测到 DisconectedContext

标签 c# winforms excel-interop

我需要帮助来摆脱这个错误:

"Transition into COM context 0x465608 for this RuntimeCallableWrapper failed with the following error: System call failed. (Exception from HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED)). This is typically because the COM context 0x465608 where this RuntimeCallableWrapper was created has been disconnected or it is busy doing something else. Releasing the interfaces from the current COM context (COM context 0x465498). This may cause corruption or data loss. To avoid this problem, please ensure that all COM contexts/apartments/threads stay alive and are available for context transition, until the application is completely done with the RuntimeCallableWrappers that represents COM components that live inside them."

在这段代码的执行过程中发生:

int i = 2;

while(i <= lastRowPOPT)
{
     RefDocNo = poptSheet.Cells[i, 1].Text;
     RefItem = poptSheet.Cells[i, 2].Text;
     Plnt = poptSheet.Cells[i, 3].Text;
     concat = RefDocNo + RefItem + Plnt;
     poptSheet.Cells[i, 8] = concat;
     poptSheet.Range["E" + i, "G" + i].Copy(Type.Missing);
     poptSheet.Range["I" + i, "K" + i].PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteAll);

     i++;
}

大约有 4700 行,它在 1000 行和其他内容上完成工作,然后将其抛出。执行也持续了大约 4 分钟,但我认为大部分时间它都停止了。

最佳答案

我想通了。显然,当外部进程(在本例中为 Excel)运行时间过长时,操作系统认为它已经接管并且不允许其他应用程序运行。诊断很糟糕,但解决方案非常简单。在一处或多处添加以下代码行,以允许其他进程执行,现在长执行无问题完成。

System.Windows.Forms.Application.DoEvents()

关于c# - 检测到 DisconectedContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22606666/

相关文章:

c# - 时间跨度计算差异

c# - 如何使用 C# 创建 JSON post 到 api

c# - 在不关注 TabControl 选项卡的情况下循环

c# - 将凭据发送到 WebBrowser

c# - 使用 TreeView 上的 StateImageList 防止颜色渗色

c# - 从无序点绘制连续线

c# - 改进 LINQ to EF 生成的 SQL 查询

c# - C# 将对象转换为二维数组

c# - 在Excel中获取删除的范围

.NET 4.0 Excel Interop 与动态集合相关的问题