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
}
}
}
You cannot resize an array in C#, but using Array. Resize you can replace the array with a new array of different size.
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.
There are no thread-safe containers (array, list, map ...) in the standard C++ library, which could be used in multiple threads without additional locks.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With