模拟错误"基础连接已关闭:连接意外关闭。"

时间:2015-03-20 10:49:48

标签: c# exception-handling microsoft-dynamics

我正在运行一个漫长的过程,它会在Microsoft Dynamics CRM 4中逐步更新一些机会。有时,这会在错误中途停止:"底层连接已关闭:连接意外关闭了。" 由于它的间歇性,我认为是因为网络突然发生但不确定。在任何情况下,如果我重新启动过程(从停止的位置开始),它会立即重新启动。

我已经编写了以下代码来尝试应对这种情况,因为我希望这是一个过夜的过程(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块上的断点如果它在执行更新时中断但是它没有&#39;吨。那么,有没有办法模拟这个错误,所以我可以测试我的新代码?

1 个答案:

答案 0 :(得分:1)

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