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?
Use the ToArray method on ConcurrentQueue.
http://msdn.microsoft.com/en-us/library/dd267275(v=vs.110).aspx
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