我有一个使用Exceptions的WCF服务返回错误的结果。例如,当方法的参数错误时,引发异常并向客户端发送异常,客户端捕获该异常并显示其消息。我也使用FaultException。但问题是当引发异常时,服务类的析构函数不会被调用。当发生异常时,我必须在析构函数中处理存储库。我怎么能这样做?
public class TestService : ITestService
{
private AccountReposiory _accountReposiory;
public TestService()
{
Console.WriteLine("Started!");
_accountReposiory = new AccountReposiory();
}
public void DoWork()
{
//Exception Occurred!;
throw new Exception("Some Exception");
//...
}
~TestService()
{
Console.WriteLine("Finished!");
_accountReposiory.Dipose();
}
}
答案 0 :(得分:0)
不要使用析构函数,因为.net C#是托管语言
GC类自动调用,然后任何类初始化,
使用....,
try{ Console.WriteLine("Exception Occurred!"); }catch(Execption ex){ return; } try{ Console.WriteLine("Exception Occurred!"); }catch{ }
阻止解决这个问题。不要使用析构函数。我认为它可以帮到你
答案 1 :(得分:0)
进行清理总是一件好事,除非不需要,并且如果它会增加代码的开销。
在您的情况下,我想您要确保在使用后因使用非托管系统资源而销毁该类。在这种情况下,the answer in this question可能会对您有所帮助:
如果您没有使用非托管系统资源,那么您可以将清理工作留给垃圾收集器。