Shallow copy segment of array of value types

I am trying to make a shallow copy of double [] in segments and pass these segments to new threads, for example:

for (int i = 0; i < threadsArray.Length; i++) { sub[i] = new double[4]; //Doesn't shallow copy since double is a value type Array.Copy(full, i * 4, sub[i], 0, 4); double[] tempSub = sub[i]; threadsArray[i] = new Thread(() => DoStuff(tempSub)); threadsArray[i].Start(); } 

What would be the best way for the created segments to reference the original array?

+4
source share
1 answer

You can use the ArraySegment<T> structure:

 for (int i = 0; i < threadsArray.Length; i++) { sub[i] = new ArraySegment<double>(full, i * 4, 4); ArraySegment<double> tempSub = sub[i]; threadsArray[i] = new Thread(() => DoStuff(tempSub)); threadsArray[i].Start(); } 

(note that you will need to change the DoStuff signature to accept an ArraySegment<double> (or at least IList<double> instead of an array)

ArraySegment<T> does not copy data; it simply represents the segment of the array, while maintaining a reference to the original array, offset and count. Starting with .NET 4.5, it implements IList<T> , which means that you can use it without worrying about how to manipulate offset and quantity.

In pre-.NET 4.5, you can create an extension method to easily list ArraySegment<T> :

 public static IEnumerable<T> AsEnumerable<T>(this ArraySegment<T> segment) { for (int i = 0; i < segment.Count; i++) { yield return segment.Array[segment.Offset + i]; } } ... ArraySegment<double> segment = ... foreach (double d in segment.AsEnumerable()) { ... } 

If you need to access elements by index, you need to create a wrapper that implements IList<T> . Here's a simple implementation: http://pastebin.com/cRcpBemQ

+2
source

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


All Articles