同步访问sql server SQLCLR中的静态变量
我编写了一个集成在sql server中的程序集,提供了一些用C#编写的存储过程。该程序集有一个只读静态变量,保存一些配置数据。该数据通过存储过程进行操作,这些存储过程也是由程序集提供的。显然我必须同步对该静态变量的访问。 使用
lock(someGuard)
{
// ... access static configuration
}
我尝试在我的配置类中 。但随后我收到 HostProtectionException,告诉我程序集必须以完全信任的方式运行才能执行此操作。有更好的方法吗?
I have written an assembly which is integrated in sql server, providing some stored procedures written in C#. The assembly has a readonly static variable holding some configuration data. This data is manipulated via stored procedures, which are also provided by the assembly. Obviously I have to synchronize access to this static variable. I tried to use
lock(someGuard)
{
// ... access static configuration
}
inside my configuration class. But then I get a HostProtectionException, telling me, that the assembly has to run with full trust to do that. Is there a better way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上有一个未记录的黑客:用 < 装饰类代码>编译器生成属性。与任何未记录的解决方法一样,效果可能会因未来版本的不同而有所不同。
不过,您不需要这个,如果静态是只读的,那么您可以将其声明为只读,并且程序集将很好地部署,安全程序集中接受只读静态。而且是真正的只读,锁卫也是不必要的。
如果您无法将其标记为只读并删除锁定,则意味着它不是只读的,您将处于移动的沙地区域。您可能会阻止 SQL 工作线程并产生不可预测的结果(因此存在 UNSAFE 要求)。仅当您完全理解其含义时,才应该非常小心地使用 CompilerGenerate 技巧。您需要
锁
这一事实强烈表明您的代码对于 SQL 和静态实际上是不安全的。There is actually an undocumented hack: decorate the class with the
CompilerGenerated
attribute. As with any undocumented workarounds, mileage may vary with future releases.You shouldn't need this though, if the static is readonly then you can declare it readonly and the assembly will deploy fine, readonly statics are accepted in SAFE assemblies. And is truly readonly, the lock guard is also unnecessary.
If you cannot mark it readonly and remove the lock, it means is not readonly and you will be on moving sands territory. You can block SQL workers and have unpredictable results (hence the UNSAFE requirement). The CompilerGenerated trick should really be used with a lot of care, onyl if you understand perfectly the implications. The fact that you need a
lock
is a strong indicator your code is actually unsafe wrt to SQL and statics.解决此限制的唯一方法是将程序集部署为 UNSAFE。尽管如此,静态共享数据仍然不符合建议:
The only way around this restriction is to deploy the assembly as UNSAFE. Still, static shared data is against recommendations: