我有以下代码由 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
}
}
但是,我不喜欢捕获所有这样的异常(我知道这是不好的做法)。解决这个问题的最佳方法是什么?
我应该捕捉到特殊的例外吗?或者,现在是实现 using 语句的好时机吗(如果可以,我可以提供一些帮助)吗?