如何确保线程安全的ASP.net页面访问静态对象列表

时间:2011-11-23 10:02:43

标签: c# asp.net .net synchronization thread-safety

在我的网络应用程序中,我为所有在线用户提供以下常用对象列表。

public static List<MyClass> myObjectList = new List<MyClass>();

因此,当多个在线用户尝试读取来自此对象 myObjectList 的数据时,是否存在线程同步问题的可能性。

在另一种情况下,多个用户正在阅读 myObjectList ,其中很少有人也在写,但每个用户都在使用不同的索引列表。每个用户都可以在此列表中添加新项目。所以现在我认为有可能出现同步问题

如何编写可以更安全地从该对象读取和写入数据的线程安全实用程序类。

非常欢迎建议

Angelo建议的代码看起来像这样

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;


namespace ObjectPoolExample
{
    public class ObjectPool<T>
    {
        private ConcurrentBag<T> _objects;
        private Func<T> _objectGenerator;

        public ObjectPool(Func<T> objectGenerator)
        {
            if (objectGenerator == null) throw new ArgumentNullException("objectGenerator");
            _objects = new ConcurrentBag<T>();
            _objectGenerator = objectGenerator;
        }

        public T GetObject()
        {
            T item;
            if (_objects.TryTake(out item)) return item;
            return _objectGenerator();
        }

        public void PutObject(T item)
        {
            _objects.Add(item);
        }
    }

    class Program
    {
       static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            // Create an opportunity for the user to cancel.
            Task.Factory.StartNew(() =>
                {
                    if (Console.ReadKey().KeyChar == 'c' || Console.ReadKey().KeyChar == 'C')
                        cts.Cancel();
                });

            ObjectPool<MyClass> pool = new ObjectPool<MyClass> (() => new MyClass());            

            // Create a high demand for MyClass objects.
            Parallel.For(0, 1000000, (i, loopState) =>
                {
                    MyClass mc = pool.GetObject();
                    Console.CursorLeft = 0;
                    // This is the bottleneck in our application. All threads in this loop
                    // must serialize their access to the static Console class.
                    Console.WriteLine("{0:####.####}", mc.GetValue(i));                 

                    pool.PutObject(mc);
                    if (cts.Token.IsCancellationRequested)
                        loopState.Stop();                 

                });
            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
        }

    }

    // A toy class that requires some resources to create.
    // You can experiment here to measure the performance of the
    // object pool vs. ordinary instantiation.
    class MyClass
    {
        public int[] Nums {get; set;}
        public double GetValue(long i)
        {
            return Math.Sqrt(Nums[i]);
        }
        public MyClass()
        {
            Nums = new int[1000000];
            Random rand = new Random();
            for (int i = 0; i < Nums.Length; i++)
                Nums[i] = rand.Next();
        }
    }   
}

我想我可以采用这种方法。

1 个答案:

答案 0 :(得分:3)

如果您使用的是.NET 4.0,最好更改为运行时已经支持的thread-safe collections之一,例如ConcurrentBag

如果我没记错的话,并发包不支持按索引访问,因此如果您需要通过给定密钥访问对象,则可能需要求助ConcurrentDictionary

如果.NET 4.0不是一个选项,您应该阅读以下博文:

Why are thread safe collections so hard?