线程本地存储为C#类库 [英] Thread Local Storage For C# Class Library

查看:117
本文介绍了线程本地存储为C#类库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常古老但非常大的库,我正在考虑将其转换为C#类库。现有的库使用存储在TLS中的大量全局变量。 C#没有真正的全局变量概念,但是一种解决方法是使用一个叫做GlobalVar的静态类,并将它们全部放在这个类中,这样它们可以通过GlobalVar.xxxxxx来访问。



<但是,我的想法是,这将破坏所有正在转换的代码,因为GlobalVar类将是普通的全局类,而不是每个线程的存储。有没有办法让这些全局变量成为每个线程?即在C#中静态__declspec(thread)的等价物是什么?



我应该在这一点上添加我讨厌全局变量。我认为他们往往是糟糕的设计的结果。但是,由于时间紧迫的限制,第一阶段是将库转换为C#,但最小的麻烦是,然后第二阶段将重新设计它们。

解决方案

ThreadLocal 类(在4.0中引入)和 ThreadStaticAttribute



ThreadStaticAttribute 只能用于 static 字段。 ThreadLocal 类可用于普通字段,但速度较慢。 请注意,如果你不喜欢不能控制你所在的线程(例如,你是ASP.NET的一个页面,你从一个随机预先使用的线程开始,或者你是一个ThreadPool的线程),那么你的线程静态(一般来说,不是属性)变量将被预先初始化为前一个线程的旧值。 (请参阅两种技术的故事:[ThreadStatic] Attribute和System.Web.HttpContext.Current .Items



我忘了,有 Thread.AllocateDataSlot 与其他目标相似的目标。


I have a very old but very large library which I am considering converting to a C# class library. The existing library uses a lot of global variables stored in the TLS. C# has no real concept of global variables but one workaround is to use a static class called something like GlobalVar and put them all in this class so they can be accessed via GlobalVar.xxxxxx

However, my thinking is that this will break all the existing code which is being converted as the GlobalVar class will be a normal global class and not per thread storage. Is there a way of getting these globals to be per thread? i.e. what is the equivalent of __declspec (thread) static in C#?

I should add at this point that I hate global variables. I think they are often the result of poor design. However, due to tight time restrictions, phase one is to convert the library to C# with minimum fuss and then phase 2 will be to redesign them properly.

解决方案

There are the ThreadLocal class (introduced in 4.0) and the ThreadStaticAttribute.

The ThreadStaticAttribute can be used only on static fields. The ThreadLocal class can be used on "normal" fields but it is slower.

Be aware that if you don't control the thread you are on (for example you are a page of ASP.NET and you start on a "random" pre-used thread, or you are a thread of a ThreadPool), then your "thread-static" (in general, not the attribute) variables will be pre-initialized with the old values of the previous thread. (see for example A tale of two techniques: The [ThreadStatic] Attribute and System.Web.HttpContext.Current.Items)

I was forgetting, there is the Thread.AllocateDataSlot that has similar "objectives" than the others.

这篇关于线程本地存储为C#类库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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