C# 是否有“ThreadLocal"?模拟(对于数据成员)到“ThreadStatic";属性?

Does C# have a quot;ThreadLocalquot; analog (for data members) to the quot;ThreadStaticquot; attribute?(C# 是否有“ThreadLocal?模拟(对于数据成员)到“ThreadStatic;属性?)

本文介绍了C# 是否有“ThreadLocal"?模拟(对于数据成员)到“ThreadStatic";属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现 "ThreadStatic" 属性非常有用,但现在让我想要一个 "ThreadLocal" 类型属性,让我拥有基于每个线程的非静态数据成员.

I've found the "ThreadStatic" attribute to be extremely useful recently, but makes me now want a "ThreadLocal" type attribute that lets me have non-static data members on a per-thread basis.

现在我知道这会产生一些重要的影响,但是:

Now I'm aware that this would have some non-trivial implications, but:

C#/.net 中是否已经内置了这样的东西? 或者因为到目前为止似乎答案是否定的(对于 .net <4.0),是否存在有一个常用的实现吗?

我可以自己想出一种合理的方法来实现它,但如果可用的话,我只会使用已经存在的东西.

I can think of a reasonable way to implement it myself, but would just use something that already existed if it were available.

稻草人示例,如果它尚不存在,它将实现我正在寻找的东西:

Straw Man example that would implement what I'm looking for if it doesn't already exist:

class Foo
{
    [ThreadStatic] 
    static Dictionary<Object,int> threadLocalValues = new Dictionary<Object,int>();
    int defaultValue = 0;

    int ThreadLocalMember
    {
         get 
         { 
              int value = defaultValue;
              if( ! threadLocalValues.TryGetValue(this, out value) )
              {
                 threadLocalValues[this] = value;
              }
              return value; 
         }
         set { threadLocalValues[this] = value; }
    }
}

请原谅任何 C# 的无知.我是一名 C++ 开发人员,最近才开始接触 C# 和 .net 更有趣的功能

Please forgive any C# ignorance. I'm a C++ developer that has only recently been getting into the more interesting features of C# and .net

我仅限于 .net 3.0,也许是 3.5(项目已经/即将迁移到 3.5).

I'm limited to .net 3.0 and maybe 3.5 (project has/will soon move to 3.5).

特定用例是线程特定的回调列表(使用虚构的 [ThreadLocal] 属性) a la:

Specific use-case is callback lists that are thread specific (using imaginary [ThreadLocal] attribute) a la:

class NonSingletonSharedThing
{
     [ThreadLocal] List<Callback> callbacks;

     public void ThreadLocalRegisterCallback( Callback somecallback )
     {    
         callbacks.Add(somecallback);    
     }

     public void ThreadLocalDoCallbacks();
     {    
         foreach( var callback in callbacks )  
            callback.invoke();  
     }
}

推荐答案

进入.NET 4.0!

如果您卡在 3.5(或更早版本),则有 一些功能 你应该看看,比如 AllocateDataSlot 应该做你想做的事.

If you're stuck in 3.5 (or earlier), there are some functions you should look at, like AllocateDataSlot which should do what you want.

这篇关于C# 是否有“ThreadLocal"?模拟(对于数据成员)到“ThreadStatic";属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# 是否有“ThreadLocal"?模拟(对于数据成员)到“ThreadStatic";属性?

基础教程推荐