Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Array.Resize(..) threadsafe?

Tags:

c#

Is calling Array.Resize on an array that is being used as a buffer for SAEA threadsafe? different threads all write to their own assigned part of the array, I just want to make the array bigger without locking once the initialized size runs out as connected users increase.

byte[] buffer; //Accessed
object expand_Lock = new object();

public void AsyncAccept()
{
    //Lock here so we don't resize the buffer twice at once
    lock(expand_Lock)
    {
        if (bufferFull)
        {
            Array.Resize(buffer, buffer.Length + 2048 * 100); //Add space for 100 more args
            //Is Array.Resize threadsafe if buffer can be read/wrote to at anytime?
            AssignMoreSAEA(2048, 100); //irrelevant to question what this does
        }
    }
}
like image 225
Vans S Avatar asked May 01 '14 16:05

Vans S


People also ask

Can arrays be resized in C#?

You cannot resize an array in C#, but using Array. Resize you can replace the array with a new array of different size.

Is array copy thread-safe?

An int[] is an object and it's mutable because the getArray() method returns a direct reference to it. Therefore, this class is not thread safe. To make it safe, you'd have to return a copy of the array instead.

Is array thread-safe in C++?

There are no thread-safe containers (array, list, map ...) in the standard C++ library, which could be used in multiple threads without additional locks.

Is list thread-safe C#?

Thread Safe List With the ConcurrentBag Class in C# The ConcurrentBag class is used to create a thread-safe, unordered collection of data in C#. The ConcurrentBag class is very similar to the List in C# and can be used as a thread-safe list in C#. To use the ConcurrentBag class, we have to import the System.


1 Answers

No, Array.Resize is not thread-safe. The array that's being resized may have to be moved around in memory and the resized array will not even be the same array as the one passed in.

This means that one thread may be writing into the original array while Array.Resize is creating the new array and copying over items - the copy operation is not protected. This can result in loss of data.

like image 109
xxbbcc Avatar answered Oct 02 '22 00:10

xxbbcc