2

这个问题的两个小部分,希望能为我消除一些歧义。

首先,哪个更适合调用 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){
     .......
}

我想知道的是,我是否应该始终将服务调用包装在 using 块中?如果服务引发异常,是否会调用 IDisposable.Dispose()?

4

2 回答 2

4

看看这个问题。

您还可以创建几个类,例如

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());
于 2012-06-15T08:29:30.523 回答
2

using处理 WCF 代理时不要使用。原因之一是Dispose()will call如果代理处于状态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();
}
于 2012-06-15T08:26:39.400 回答