我有一個實時應用程序,可以跟蹤全國各地許多網站的資產。作爲該解決方案的一部分,我有8個客戶端應用程序更新中央服務器。處理WCF超時的最佳方式
我的問題是,有時應用程序會失去與中央服務器的連接,我想知道處理這個問題的最佳方法是什麼?我知道我可以增加最大發送/接收時間來處理超時,但我也想要一個優雅的解決方案來處理,如果連接到服務器關閉:
例如我打電話給我這樣的服務:
using (var statusRepository = new StatusRepositoryClient.StatusRepositoryClient())
{
statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
}
我想添加一個try/catch這樣的......
using (var statusRepository = new StatusRepositoryClient.StatusRepositoryClient())
{
try
{
statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
}
catch (TimeoutException timeout)
{
LogMessage(timeout);
}
catch (CommunicationException comm)
{
LogMessage(comm);
}
}
處理這種方式不允許我重新運行代碼,而無需一噸碼重複。任何人有任何建議?
編輯:縱觀Sixto Saez和user24601有一個整體解決方案的答案比在單個異常級別上處理超時要好,但是......我在考慮下面的問題會解決我的問題(但它會添加一個TON的額外代碼錯誤處理):
void Method(int statusId)
{
var statusRepository = new StatusRepositoryClient.StatusRepositoryClient()
try
{
IsServerUp();
statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
statusRepository.Close();
}
catch (Exception ex)
{
statusRepository.Abort();
if (ex is TimeoutException || ex is CommunicationException)
{
LogMessage(timeout);
Method(statusId);
}
else
{
throw new Exception(ex.Message + ex.InnerException);
}
}
}
}
bool IsServerUp()
{
var x = new Ping();
var reply = x.Send(IPAddress.Parse("127.0.0.1"));
if (reply == null)
{
IsServerUp();
}
else
{
if (reply.Status != IPStatus.Success)
{
IsServerUp();
}
}
return true;
}
您可以編寫一個函數來測試服務器是否啓動,這樣您可以在連接到資源庫之前檢查服務器是否已啓動。你也可以看看直到服務器啓動。 – Jethro
因此,做一個遞歸函數,不退出,直到服務器,然後繼續......並在任何wcf調用之前彈出呼叫?我喜歡這個想法,並且它比上面提到的編輯代碼要少。您的想法絕對可以提高99%的可靠性,但是如果服務器在檢查和方法調用之間失去連接,我該如何處理呢? –
@Jethro:最佳做法建議不要使用ping方法。看到這裏的討論:http://stackoverflow.com/questions/2166356/how-to-check-if-a-wcf-service-is-operational基本的想法是,超時可能是一個服務依賴的結果,它wouldn不會顯示在ping事件中(例如與數據庫導致超時的數據庫交互的WCF服務) – VoteCoffee