打开/关闭Web服务

时间:2011-11-16 15:38:35

标签: c# asp.net wcf web-services

我有服务。我们正在向此服务发送记录。但是,当我们发送太多记录(3,000)时,服务会超时。我的想法是打破记录并打开服务,然后每1000条记录关闭它。

然而,我收到一个错误:

{"Cannot access a disposed object.\r\nObject name: 'System.ServiceModel.Channels.ServiceChannel'."}

这是我的代码:

ServiceClient client = new ServiceClient();
foreach (Record rc in creditTransactionList)
{
    //if we are not on the last one...
    if (currentTransCount < totalTransCount)
    {
        //Current batch count is less than 1,000
        if (currentBatchCount <= amountPerBatch)
        {
            currentBatchCount++;
            if (rc != null)
                client.RecordInsert(rc);
        }
        //Current batch count is 1,000
        if (currentBatchCount == amountPerBatch)
        {
            currentBatchCount = 0;
            client.Close();
            client.Open();
        }
        //Increment Total Counter by 1
        currentTransCount++;
    }
    else
    {
        currentBatchCount++;
        if (rc != null)
            client.RecordInsert(rc);
        client.Close();
    }
}

amountPerBatch = 1000;
totalTransCount = ACHTransactionList.Count();
currentBatchCount = 0;
currentTransCount = 1;

foreach (Record rc in ACHTransactionList)
{
    //if we are not on the last one...
    if (currentTransCount < totalTransCount)
    {
        //Current batch count is less than 1,000
        if (currentBatchCount <= amountPerBatch)
        {
            currentBatchCount++;
            if (rc != null)
                client.RecordInsert(rc);
        }
        //Current batch count is 1,000
        if (currentBatchCount == amountPerBatch)
        {
            currentBatchCount = 0;
            client.Close();
            client.Open();
        }
        //Increment Total Counter by 1
        currentTransCount++;
    }
    else
    {
        currentBatchCount++;
        if (rc != null)
            client.RecordInsert(rc);
        client.Close();
    }
}

我创建了一个示例控制台应用程序来执行此操作,但是当我实际将其与实际服务合并到实际项目中时,我收到错误。你能帮我弄清楚我做错了什么。它必须是我的client.open和client.close,是我的猜测。非常感谢任何帮助!!

3 个答案:

答案 0 :(得分:8)

我会尝试更像这样的东西...... 请注意,您也应始终.Dispose()客户端。此外,如果发生错误,则.Close()不再适用于客户端,而是必须.Abort()

ServiceClient client = new ServiceClient();
try
{
  foreach(...)
  {
    ...
    //Current batch count is 1,000
    if (currentBatchCount == amountPerBatch)
    {
        currentBatchCount = 0;
        client.Close();
        client = new ServiceClient();
    }
    ...
  }
}
finally
{
  if(client.State == CommunicationState.Faulted)
    client.Abort();
  else
    client.Close();
}

答案 1 :(得分:1)

client.Close将处置该对象。 client.Open之后总会抛出错误。 您需要使用new ServiceClient();

初始化客户端

答案 2 :(得分:0)

我所做的是检查客户端的状态并在必要时重置它:

if (wsClient.State.Equals(CommunicationState.Faulted) || wsClient.State.Equals(CommunicationState.Closed) || wsClient.State.Equals(CommunicationState.Closing))
                {
                    wsClient = new ServiceClient();
                }