模拟错误 "The underlying connection was closed: The connection was closed unexpectedly."

Simulate error "The underlying connection was closed: The connection was closed unexpectedly."

我是 运行 一个漫长的过程,它在 Microsoft Dynamics CRM 4 中逐一更新一些机会。有时这会中途停止并出现错误:"The underlying connection was closed: The connection was closed unexpectedly." 由于它是间歇性的,我认为这是由于网络故障而发生的事情,但不确定。在所有情况下,如果我重新启动该过程(从它停止的地方开始),它会立即重新开始。

我已经编写了以下代码来尝试应对这种情况,因为我希望这是一个通宵的过程(1 关):

int Retries = 0;
bool Ready = false;
while (!Ready && Retries < 5)
{
    try
    {
        using (CrmService service = GetCrmServiceInstance())
        {
            service.Update(opp);
            Ready = true; //break out of the while loop as connection is working.
        }
    }
    catch (SoapException se)
    {
        Retries++;
        if (Retries > 4)
        {
            throw new Exception("Error occurred updating opportunity " + opp.opportunityid.Value + ". Error: " + se.Detail.InnerXml);
        }
    }
    catch (Exception ex)
    {
        Retries++;
        if (Retries > 4)
        {
            throw new Exception("Error occurred updating opportunity " + opp.opportunityid.Value + ". Error: " + ex.Message);
        }
    }
}

我的理论是,如果它最初收到此错误,它将重试更新并希望再次工作。如果重试次数超过4则抛出错误。

我现在想测试这段代码,看看它是否足以满足我的目的。我已经尝试了 运行 漫长的过程(6 小时)来查看我是否收到错误,在 SoapException 和 Exception 块上有断点,如果它在执行更新时中断但它没有'吨。那么,有没有办法模拟这个错误,以便我可以测试我的新代码?

模拟连接失败的一种方法是重新启动 CRM 应用程序池,默认情况下为 CrmAppPool。