如何从自托管wcf服务抛出FaultException?

时间:2011-04-09 18:21:53

标签: c# wcf fault self-hosting

我打算在Windows服务中托管服务,但我正在考虑标题中描述的问题。有人有类似的问题吗? 感谢

更新

问题是,当您在WinForms / WPF / Win Service应用程序中抛出异常时,程序崩溃,您将不得不重新启动它。

2 个答案:

答案 0 :(得分:1)

异常并不总是导致服务器崩溃。即使是意外的服务器端异常也会传输到客户端。然而,它被认为比预期的更严重,导致频道错误。

基本思想是在接口契约中包含预期的异常(故障)。有很多方法可以做到这一点,这里是an introduction article

当然,您需要在服务器上进行适当的异常处理。

答案 1 :(得分:0)

您可以尝试的是通过挂钩到Host应用程序的主方法入口点中的ThreadException事件来拦截任何异常,以检查它是否是FaultException。

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());

        // Hook to this event below
        Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
    }

    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        if (e.Exception is FaultException)
            return; // Bypass FaultExceptions;
        else
            throw e.Exception; // Throw otherwise
    }
}