Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe way to copy ConcurrentQueue

Basically I want to achieve this:

private ConcurrentQueue<FormData> _formsData;

private void SaveForms()
{
    var serializer = new DataContractSerializer(_formsData.GetType());
    serializer.WriteObject(fileStream, _formsData);
}

But I assume it is not thread-safe to pass ConcurrentQueue as object parameter. So I need first to copy whole queue to another collection in a safe way, and then pass this new collection to WriteObject.

I found CopyTo method of ConcurrentQueue, which seems to be thread-safe. But it requires a pre-initialized array, so the code would be:

var data = new FormData[_formsData.Count];
_formsData.CopyTo(data, 0);

which again seems to be not safe (number of elements can be changed by other thread between Count and CopyTo call).

So is there a thread-safe way to copy ConcurrentQueue?

like image 399
Aleksey Shubin Avatar asked Aug 27 '26 07:08

Aleksey Shubin


1 Answers

Use the ToArray method on ConcurrentQueue.

http://msdn.microsoft.com/en-us/library/dd267275(v=vs.110).aspx

like image 102
Brian Avatar answered Aug 29 '26 21:08

Brian