类型初始化(静态构造函数)的异常处理 [英] Type initializer (static constructor) exception handling

查看:318
本文介绍了类型初始化(静态构造函数)的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在C#中的WCF服务。最初,我实现了一个静态构造函数做一些一次性初始化,但一些正在做可能(暂时的)失败的初始化。

I'm writing a WCF service in C#. Initially my implementation had a static constructor to do some one-time initialization, but some of the initialization that is being done might (temporarily) fail.

看来,静态构造函数只调用一次,即使第一个(失败的)尝试抛出一个异常?任何后续尝试实例我的类将立即失败,一个 TypeInitializationException 无code实际被执行。

It appears that static constructors are only called once, even if the first (failed) attempt threw an exception? Any subsequent attempts to instantiate my class will immediately fail with a TypeInitializationException without the code actually being executed.

C#语言规范规定,静态构造函数至多一次,但基本上这使得在那里,你永远不能从恢复的错误例外,就算你抓到了吗?

The C# language specification states that a static constructor is called at most once, but basically this makes an exception in there an error that you cannot ever recover from, even if you catch it?

我失去了一些东西呢?我想我应该搬到任何远程危及该服务的实例构造和手动检查是否将类的初始化已经成功地完成了前面?

Am I missing something here? I suppose I should move anything remotely dangerous to the service's instance constructor and manually check whether or not the class initialization was already succesfully completed earlier?

推荐答案

所以,你可以包装在try / catch语句和至少关键部分,这意味着该类型不会无法完成初始化,但肯定如果初始化code是重要的,那么这种行为其实是不错的 - 类型是不是在这个初始化状态下使用

So you could wrap the critical parts in try/ catch and at least that means the type won't fail to initialize, but surely if the initialization code is that critical, then this behavior is actually good - the type is not usable in this uninitialized state.

另一种选择是做一个单身 - 每一次尝试,让你可以正确地创建类型的实例,直到你成功了,即使它无法在第一时间

The other option is to do it as a singleton - each time you try and get the Instance you can create the type correctly, until you are successful, even if it fails the first time.

您仍然需要一些错误处理的情况下实例返回空的第一个(或第二等)时调用者。

You would still need some error handling on the caller in case Instance returns you null the first (or second etc.) time.

编辑:如果你不想单身,那么只需要您的实例构造函数初始化静态部分

And if you don't want a singleton, then just have your instance constructor initialize the static parts

例如。

private object _lock = new object()
private bool _initialized;

public T()
{
   lock(_lock)
   {
      if(!_initialized)
      {
         try
         {
           //Do static stuff here
         }
         catch(Exception ex_)
         {
           //Handle exception
         }
      } 
   }
}

这篇关于类型初始化(静态构造函数)的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆