WCF致电 - 最佳实践

时间:2012-06-15 08:02:36

标签: c# wcf using

这个问题的两个小部分,希望能为我澄清一些含糊之处。

首先,哪个更适合调用WCF服务?

using (var myService = new ServiceClient("httpBinding")){
     try{         
          var customerDetails = GetCustomerDetails();
          var results = myService.GetCustomerPurchases(customerDetails);
     }catch(Exception e){
          ......
     }
}

var myService = new ServiceClient("httpBinding");
try{
     var customerDetails = GetCustomerDetails();
     var results = myService.GetCustomerPurchases(customerDetails);
}catch(Exception e){
     .......
}

我想知道的是,我是否应该始终将服务呼叫包含在使用块中?如果服务抛出异常,是否会调用IDisposable.Dispose()?

2 个答案:

答案 0 :(得分:4)

查看this问题。

您还可以创建几个类,如

public class ClientService<TProxy>
{
    private static ChannelFactory<TProxy> channelFactory = new ChannelFactory<TProxy>("*");

    public static void SendData(Action<TProxy> codeBlock)
    {
        var proxy = (IClientChannel) channelFactory.CreateChannel();
        bool success = false;

        try
        {
            codeBlock((TProxy)proxy);
            proxy.Close();
            success = true;
        }
        finally
        {
            if (!success)
            {
                proxy.Abort();
            }
        }
    }

    public static TResult GetData<TResult>(Func<TProxy, TResult> codeBlock)
    {
        var proxy = (IClientChannel) channelFactory.CreateChannel();
        bool success = false;

        TResult result;
        try
        {
            result = codeBlock((TProxy)proxy);
            proxy.Close();
            success = true;
        }
        finally
        {
            if (!success)
            {
                proxy.Abort();
            }
        }

        return result;
    }
}

public class SomeAnotherService<TProxy>
{
    public static bool SendData(Action<TProxy> codeBlock)
    {
        try
        {
            ClientService<TProxy>.SendData(codeBlock);
            return true;
        }
        catch(Exception ex)
        {
            //...
        }
        return false;
    }

    public static TResult GetData<TResult>(Func<TProxy, TResult> codeBlock)
    {
        TResult result = default(TResult);
        try
        {
            result = ClientService<TProxy>.GetData(codeBlock);
        }
        catch (Exception ex)
        {
            //...
        }

        return result;
    }
}

有时它很方便。以下是调用某些服务方法的示例。

var someObj = SomeAnotherService<IMyService>.GetData(x => x.SomeMethod());

答案 1 :(得分:2)

处理WCF代理时不要使用using。其中一个原因是Dispose()将调用Close(),如果代理处于Faulted状态,则会引发异常。所以最好的用法是这样的:

var myService = new ServiceClient("httpBinding");

try
{
    myService.SomeMethod();
}
catch
{
    // in case of exception, always call Abort*(
    myService.Abort();

    // handle the exception
    MessageBox.Show("error..");
}
finally
{
    myService.Close();
}