How to properly close a client proxy (An existing connection was forcibly closed by the remote host)?

我是研究僧i 提交于 2019-11-29 01:53:02

To resolve this error, simply close the Channel Factory as well.

private async Task<string> TestTask()
{
    Service1Client proxy = null;

    try
    {
        Console.WriteLine("Calling service");

        proxy = new Service1Client();
        return await proxy.DoWorkAsync();
    }
    finally
    {
        if (proxy.State != System.ServiceModel.CommunicationState.Faulted)
        {
            Console.WriteLine("Closing client");
            proxy.ChannelFactory.Close();
            proxy.Close();
        }
        else
        {
            Console.WriteLine("Aborting client");
            proxy.Abort();
        }
    }
}

Edit Ok. I was able to reproduce the problem using your code. The good news is that I also stumbled upon a way to not reproduce it. I do not think that you have any problem in your code. I think that the error is being logged because you are running it in the debugger in VS; and when the debugger shutting down the service is causing the error to get logged.

Follow these steps and see if you no longer get the error (this works perfectly for me every time):

  1. Right-click on the service project and choose Debug > Start New Instance
  2. Right-click on the console application and choose Debug > Start New Instance
  3. Run the console to completion.
  4. Check your log file.
  5. Stop the service using the WCF Test Client window and not the debugger stop button.
  6. Check your log file.

Here's a link to a shock wave video of me doing the above steps: swf file

Orginal The code you posted works just fine on my system. I'm receiving no errors in any logs. As an aside, I would get rid of the catch block completely, as it is doing nothing but rethrowing the exception. Then I'd write the finally block like this below. I think it makes the code cleaner and conveys the idea to the reader that you are not doing anything if an exception is thrown.

Service1Client proxy = null;

try
{
    Console.WriteLine("Calling service");
    proxy = new Service1Client();
    return await proxy.DoWorkAsync();
}
finally
{
    if (proxy != null)
    {
        if (proxy.State == CommunicationState.Faulted)
        {
            Console.WriteLine("Aborting client");
            proxy.Abort();
        }
        else
        {
            Console.WriteLine("Closing client");
            proxy.Close();
        }
    }
}

I suspect your return command within the try block is causing execution to skip the finally block causing your connection to remain open until client shutdown causes the exception. Is this possible? Have you made sure that your finally block is executed?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!