以优化的,线程安全的方式返回数字序列

P2l*_*P2l 4 c# thread-safety

我正在寻找一些关于编写一些线程安全,优化,优雅的代码的建议来执行以下操作:

我想要一个静态方法来返回一个整数序列.因此,例如,应用程序启动,线程1调用GetSequence方法并表示它想要取3,因此它得到一个由0,1,2组成的整数数组.线程2然后调用该方法并说给我4,所以它返回3,4,5,6.多个线程可以同时调用此方法.

为了说明我正在考虑的事情,这是我对此的尝试:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SequenceNumberService
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = NumberSequenceService.GetSequence(3);

            foreach (var item in numbers)
            {
                Console.WriteLine(item.ToString());
            }

            // Writes out:
            // 0
            // 1
            // 2

            Console.ReadLine();
        }
    }

    public static class NumberSequenceService
    {
        private static int m_LastNumber;
        private static object m_Lock = new Object();

        public static int[] GetSequence(int take)
        {
            int[] returnVal = new int[take];
            int lastNumber;

            // Increment the last audit number, based on the take value.
            // It is here where I am concerned that there is a threading issue, as multiple threads
            // may hit these lines of code at the same time.  Should I just put a lock around these two lines
            // of code, or is there a nicer way to achieve this.
            lock (m_Lock)
            {
                m_LastNumber = m_LastNumber + take;
                lastNumber = m_LastNumber;
            }

            for (int i = take; i > 0; i--)
            {
                returnVal[take - i] = lastNumber - i;
            }

            return returnVal;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,我的问题是:我是以最好的方式接近这个问题,还是有另一种方法来实现这一目标?有关优化此代码的任何建议吗?

非常感谢您的帮助.

Chr*_*ain 8

您可能希望查看Interlocked类以及它的IncrementAdd方法:

public static Int32 num = 0;

public static Int32 GetSequence() 
{ 
    return Interlocked.Increment(ref num); 
}

public static IEnumerable<Int32> GetSequenceRange(Int32 count) 
{ 
    var newValue = Interlocked.Add(ref num, count);
    return Enumerable.Range(newValue - count, count);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果两个线程同时要求3个数字,则可能返回{0,2,4}和{1,3,5}.我认为这个问题要求每个序列是连续的. (2认同)