2010-08-17 28 views
3

我想知道如何安全地調用WCF Web服務方法。這兩種方法都可以接受/等同嗎?有沒有更好的辦法?如何在C#中調用Web服務方法

1路:

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

使用using(沒有雙關語)是not recommended因爲即使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()); 
+0

我總是創建WebServicesClient的一個實例,並在整個應用程序實例中使用它,它是否會導致任何問題? – 2010-08-17 11:57:53

+0

謝謝你。沒想到它太複雜了,但這看起來不錯。 – zod 2010-09-10 09:58:36

1

第二種方法稍微好一些,因爲您正在處理可能會引發異常的事實。如果你陷入困境並且至少記錄了特定的例外情況,它會更好。

但是,此代碼將阻塞,直到GetThing返回。如果這是一個快速操作,那麼它可能不成問題,但另一種更好的方法是創建一個異步方法來獲取數據。這會引發一個事件來指示完成,並且您訂閱該事件來更新UI(或者您需要做什麼)。