Статическая инициализация гарантирует одноэлементную потокобезопасность? (C#) [дубликат]

#temptable не выживает мимо конца процедуры, в которой он был объявлен, таким образом, он никогда не будет замечаться другими пользователями.

Редактирование: Heh, оказывается, что "вложенная видимость" временных таблиц работала начиная с SQL Server 7.0, но я никогда не обновлял ни одного своего кода для использования в своих интересах этого. Я предполагаю, что встречаюсь со мной - много людей, вероятно, не может вообразить ад, который был SQL Server за 6,0 и 6,5 дней...

7
задан Community 23 May 2017 в 12:30
поделиться

2 ответа

that the constructor will fully complete before any other thread can get a reference to the object?

The static initializer will be invoked once only (by the system, at least) per AppDomain, and in a synchronized way, taking "beforefieldinit" into account. So assuming you don't do anything bizarre, any static fields assigned in the static initializer should be OK; any other attempts to use the static field should get held (blocked) behind the static constructor.

the reference to the new object is assigned only after the constructor completes

It happens when it happens. Any static field initializers happen before what you typically think of as the constructor, for example. But since other threads are blocked, this shouldn't be an issue.

However:

  • if your static initializer itself passes a reference outside (by calling a method with the reference as an argument (including "arg0"), then all bets are off
  • if you use reflection to invoke the static constructor (yes, you can do this), crazyness often follows
9
ответ дан 6 December 2019 в 23:11
поделиться

Да; гарантия заключается в заявлении, что он будет выполняться только один раз для каждого домена приложения.

Это может быть небезопасно, только если оно может выполняться более одного раза; как сказано, не может, так что все хорошо :)

2
ответ дан 6 December 2019 в 23:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: