简体   繁体   中英

Correct way of Renting and Returning a multi-dimensional array in C# from shared ArrayPool?

For example, is this the correct usage scenario?

// Rent
var rentedArray = ArrayPool<int[]>.Shared.Rent(2);

rentedArray[0] = ArrayPool<int>.Shared.Rent(10);
rentedArray[1] = ArrayPool<int>.Shared.Rent(10);

// Return
foreach (var array in rentedArray)
{
    ArrayPool<int>.Shared.Return(array, true);
}

ArrayPool<int[]>.Shared.Return(rentedArray, true);

Your code is correct as far as how to use the API to rent and return arrays is being used.

You rent an array with a minimum specified length using the Rent API, store it in a variable and then returning that very same array using the Return API.

To clarify terminology, this would commonly be called a "jagged array" or array-of-arrays.

Eg:

int[][] jaggedArray = new int[2][];
jaggedArray[0] = new int[10];
jaggedArray[1] = new int[10];

Contrast with "multi-dimensional array" as it's commonly known:

int[,] dimensionalArray = new int[2,10];

It appears the ArrayPool class only deals in single-dimensional arrays, so your jagged-array approach is probably what you want.

The code is going to be less than clear.. give some thought to whether that outer-array buffer is really necessary, for your scenario.. and, if so, how to name it in a way that is readably distinct from the inner-array buffers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM