2010-05-11 50 views
0

我是WCF的新手。我以前寫過ajax來使用web服務,但在這個項目中,我嘗試使用ajax來訪問WCF。ajax與WCF工作。但幾分鐘後,不起作用

在我使用ajax構建項目和wcf後,我成功收到了返回結果。但是,10分鐘以後我沒有得到回報,ajax調用了錯誤函數,而提琴手什麼也沒有返回。

如果我重建沒有任何源修改的項目,我再次成功地收到返回。

他們是誰的經歷過這個或知道爲什麼這可能是?

謝謝。

+1

對不起我的英語不好! – 2010-05-11 13:12:03

回答

0

最有可能你沒有關閉連接。你應該將所有的呼叫都包裹在Try/Catch/Finally塊中。

在C#:

ServiceClient服務= GetService的();

 try 
     { 
      SomeRequest request = new SomeRequest(); 

      SomeResponse response = service.GetSome(request); 

      return response.Result; 
     } 
     catch (Exception ex) 
     { 
      // do some error handling 
     } 
     finally 
     { 
      try 
      { 
       if (service.State != CommunicationState.Faulted) 
       { 
        service.Close(); 
       } 
      } 
      catch (Exception ex) 
      { 
       service.Abort(); 
      } 
     } 

或VB

 Dim service As ServiceClient = GetService() 

     Try 
      Dim request As New SomeRequest() 

      Dim response As SomeResponse = service.GetSome(request) 

      Return response.Result 
     Catch ex As Exception 
      ' do some error handling 
     Finally 
      Try 
       If service.State <> CommunicationState.Faulted Then 
        service.Close() 
       End If 
      Catch ex As Exception 
       service.Abort() 
      End Try 
     End Try 
0

這裏是調用WCF服務的最佳實踐:

public static void CallService<T>(Action<T> action) where T 
      : class, ICommunicationObject, new() 
    { 
     var client = new T(); 

     try 
     { 
      action(client); 
      client.Close(); 
     } 
     finally 
     { 
      if (client.State == CommunicationState.Opened) 
      { 
       try 
       { 
        client.Close(); 
       } 
       catch (CommunicationObjectFaultedException) 
       { 
        client.Abort(); 
       } 
       catch (TimeoutException) 
       { 
        client.Abort(); 
       } 
      } 
      if (client.State != CommunicationState.Closed) 
      { 
       client.Abort(); 
      } 
     } 
    } 

每個WCF調用應該創建服務類的新實例。此代碼允許您強制執行並調用服務是這樣的:

CallService<MyService>(t => t.CallMyService()); 
+0

這也不會從服務代碼中吞下不必要的錯誤異常(您可能會拋出)。它只捕獲和處理客戶端的通信故障,並允許在服務調用周圍進行適當的異常打包,而不會與整個地方的通信通道搞混。 – 2010-06-04 15:00:40