How to call web service method in C #

I want to know how to safely call the WCF web service method. Are both of these methods acceptable / equivalent? Is there a better way?

First way:

public Thing GetThing()
{
    using (var client = new WebServicesClient())
    {
        var thing = client.GetThing();
        return thing;
    }
}

The second way:

public Thing GetThing()
{
    WebServicesClient client = null;
    try
    {
        client = new WebServicesClient();
        var thing = client.GetThing();
        return thing;
    }
    finally
    {
        if (client != null)
        {
            client.Close();
        }
    }
}

I want to make sure that the client is properly closed and deleted.

thank

+3
source share
3 answers

Using using(no pun) is not recommended because it Dispose()can even throw exceptions.

Here are a few extension methods we use:

using System;
using System.ServiceModel;

public static class CommunicationObjectExtensions
{
    public static void SafeClose(this ICommunicationObject communicationObject)
    {
        if(communicationObject.State != CommunicationState.Opened)
            return;

        try
        {
            communicationObject.Close();
        }
        catch(CommunicationException ex)
        {
            communicationObject.Abort();
        }
        catch(TimeoutException ex)
        {
            communicationObject.Abort();
        }
        catch(Exception ex)
        {
            communicationObject.Abort();
            throw;
        }
    }

    public static TResult SafeExecute<TServiceClient, TResult>(this TServiceClient communicationObject, 
        Func<TServiceClient, TResult> serviceAction)
        where TServiceClient : ICommunicationObject
    {
        try
        {
            var result = serviceAction.Invoke(communicationObject);
            return result;
        } // try

        finally
        {
            communicationObject.SafeClose();
        } // finally
    }
}

With these two:

var client = new WebServicesClient();
return client.SafeExecute(c => c.GetThing());
+4
source

, , . , , , .

, GetThing . , , . ( , ).

+1

Source: https://habr.com/ru/post/1760056/


All Articles