2013-01-18 82 views
0

我有一個answer posted by Jean-Michel Bezeau繼續處理服務

bool isAlive = false; 
string fixedAddress = "http://localhost:8732/Design_Time_Addresses/WCFService/mex"; 
System.ServiceModel.Description.ServiceEndpointCollection availableBindings = System.ServiceModel.Description.MetadataResolver.Resolve(typeof(WCFService.IAlive), new EndpointAddress(fixedAddress)); 
ChannelFactory<WCFService.IAlive> factoryService = new ChannelFactory<WCFService.IAlive>(availableBindings[0]); 
WCFService.IAlive accesService = factoryService.CreateChannel(); 
isAlive = accesService.IsAlive(); 

下面的代碼禮貌,我想我的程序繼續即使WCF服務不能達到這樣我可以通知某人通過電子郵件並將其添加到日誌。我認爲這樣做是這樣的:

bool isAlive = false; 
try 
{ 
    string fixedAddress = "http://localhost:8732/Design_Time_Addresses/WCFService/mex"; 
    System.ServiceModel.Description.ServiceEndpointCollection availableBindings = System.ServiceModel.Description.MetadataResolver.Resolve(typeof(WCFService.IAlive), new EndpointAddress(fixedAddress)); 
    ChannelFactory<WCFService.IAlive> factoryService = new ChannelFactory<WCFService.IAlive>(availableBindings[0]); 
    WCFService.IAlive accesService = factoryService.CreateChannel(); 
    isAlive = accesService.IsAlive(); 
} 
catch {} 
finally 
{ 
    if (isAlive) 
    { 
     //add success message to log 
    } 
    else 
    { 
     //add warning message to log 
     //send email notification 
    } 
} 

不過,我不喜歡追趕一樣,所有異常(我知道這是不好的做法)。什麼是最好的方式去做這件事?

是否有特殊的例外,我應該趕上?或者,現在是實施使用說明的好時機(如果有,我可以怎樣幫助一下)?

+0

您可以嘗試停止localhost上的服務並查看拋出了哪個異常。 –

+0

好的,我會這樣做的!我真的應該想到,我最好喝咖啡...... – Dean

回答

1

異常可能是很多事情 - 它可能只是一個超時,或一個404錯誤,一個500錯誤,一個連接重置錯誤......所以可能會引發一堆異常。在這種特殊情況下,我不會遇到全球性問題。

如果第一次嘗試失敗,則可能需要考慮重試,以防萬一它只是一個超時。

或者如果你已經有全局錯誤處理您的應用程序,你可能不希望吞下例外,所以你可以只使用沒有趕上finally塊:

try 
{ 
    .... 
} 
finally 
{ 
    .... 
} 

但你只希望要做到這一點,如果它是一個真正的錯誤,應用程序無法自行處理或解決。