Returning a sequence of numbers in an optimized, thread-safe manner

I'm looking for some tips for writing some stream-optimized, optimized, and elegant code to do the following:

I want the static method to return a sequence of integers. So, for example, the application starts, thread 1 calls the GetSequence method and says that it wants to accept 3, so it gets an integer array consisting of 0,1,2. Then thread 2 calls the method and says β€œgive me 4”, so it returns 3,4,5,6. Multiple threads can simultaneously call this method.

To give an idea of ​​what I'm thinking about, here is my attempt:

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; } } } 

My questions: Am I best suited to this, or is there any other way to achieve this? Any suggestions for optimizing this code?

Thanks so much for any help.

+4
source share
1 answer

You probably want to learn the Interlocked class and the Increment and Add methods:

 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); } 
+7
source

Source: https://habr.com/ru/post/1396929/


All Articles