我想知道未处理的异常是否会导致WCF服务崩溃。我编写了以下程序,该程序显示 WCF 服务启动的线程中未处理的异常将使整个 WCF 服务崩溃。
我的问题是,我想确认线程中未处理的异常(由WCF服务启动)是否会导致WCF崩溃?我的困惑是我认为 WCF 应该是稳定的服务,不应该因为未处理的异常而崩溃。
我正在使用 VSTS 2008 + C# + .Net 3.5 开发基于自托管 Windows 服务的 WCF 服务。
这是代码的相关部分,
namespace Foo
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
[ServiceContract]
public interface IFoo
{
[OperationContract]
string Submit(string request);
}
}
namespace Foo
{
// NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
public class FooImpl : IFoo
{
public string Submit(string request)
{
return String.Empty;
}
}
}
namespace Foo
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
ServiceHost host = new ServiceHost(typeof(FooImpl));
protected override void OnStart(string[] args)
{
host.Open();
// start a thread which will throw unhandled exception
Thread t = new Thread(Workerjob);
t.Start();
}
protected override void OnStop()
{
host.Close();
}
public static void Workerjob()
{
Thread.Sleep(5000);
throw new Exception("unhandled");
}
}
}
服务端未处理的异常将导致通道(客户端和服务器之间的连接)“故障” - 例如被拆毁。
从那时起,您不能再使用相同的代理客户端对象实例从客户端进行调用 - 您必须重新创建代理客户端。
最好的选择是尽可能在服务器端处理所有错误。查看错误处理程序 http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx接口,您应该在服务实现类上实现该接口,以将所有未处理的 .NET 异常转换为 SOAP 错误(这将导致NOT导致通道故障),或者完全报告/吞掉它们。
Marc
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)