3

我想知道如何安全地调用 WCF Web 服务方法。这两种方法都可接受/等效吗?有没有更好的办法?

第一种方式:

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

第二种方式:

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

我想确保客户端已正确关闭和处置。

谢谢

4

3 回答 3

4

不推荐使用using(无双关语),因为它甚至会抛出异常。Dispose()

这是我们使用的几个扩展方法:

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
    }
}

有了这两个:

var client = new WebServicesClient();
return client.SafeExecute(c => c.GetThing());
于 2010-08-17T10:44:55.797 回答
1

第二种方法稍微好一点,因为您要处理可能引发异常的事实。如果您捕获并至少记录了特定的异常,那就更好了。

但是,此代码将阻塞,直到GetThing返回。如果这是一个快速操作,那么它可能不是问题,但更好的方法是创建一个异步方法来获取数据。这会引发一个事件以指示完成,并且您订阅该事件以更新 UI(或您需要做的任何事情)。

于 2010-08-17T10:45:12.917 回答
0

不完全的:

于 2010-08-17T10:45:10.680 回答