【问题标题】:How do give a size to an array initialized with localthread如何为使用 localthread 初始化的数组指定大小
【发布时间】:2018-10-21 01:49:03
【问题描述】:

我想要一个线程本地的数组并想使用 ThreadLocal。但是如何给出数组的大小呢?

这是不可能的:

class Foo
{
    ThreadLocal<int[]> bar;
    public Foo()
    {
        bar = new ThreadLocal<int[10]>();
    }
}

【问题讨论】:

    标签: c# arrays thread-local


    【解决方案1】:

    您可以使用带有Func&lt;T&gt;“valueFactory”的构造函数来创建它:

    class Foo
    {
        ThreadLocal<int[]> bar;
        public Foo()
        {
            bar = new ThreadLocal<int[]>(() => new int[10]);
        }
    }
    

    See the MSDN page for more information

    【讨论】:

      【解决方案2】:

      ThreadLocal 中的通用参数指定要执行的任务的返回值的类型。无需提供任何大小,只需从中返回一个数组:

      bar = new ThreadLocal<int[]>(() => new int[10]);
      

      这就像你有一个返回数组的普通方法一样:

      int[] DoSomething()
      {
          return new[10] { ... };
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-04
        • 1970-01-01
        • 1970-01-01
        • 2015-07-28
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多