Search code examples
c#.netxmllinqplinq

Is it possible to use PLINQ to write to XmlWriter? Any other stream/writer?


I use PLINQ on every stage but generating an XML output. I tried and got some wacky exception. So I wonder if there is a trick that would allow me to do async output.

...
    [DataContract(Namespace = "")]
    public class MyClass
    {
        [DataMember]
        public ulong Id { get; set; }

        [DataMember]
        public int[] Value { get; set; }
    }
...
        private static readonly DataContractSerializer _serializer =
            new DataContractSerializer(typeof(MyClass));

...
            XmlDocument _resultDoc = new XmlDocument();
...
            using (var writer = _resultDoc.CreateNavigator().AppendChild())
            {
                writer.WriteStartElement("root");
                writer.WriteAttributeString("ver", "0");
                {
                    //--------------------------------------------------
                    // Want this to be:
                    // myDictionary.ToList().ToParallel().ForAll(pair =>
                    //--------------------------------------------------
                    myDictionary.ToList().ForEach(pair =>
                        _serializer.WriteObject(
                            writer, 
                            new MyClass 
                            {
                                Id = pair.Key.Id,
                                Value = pair.Value.ToArray()
                            }
                        )
                    );
                }
                writer.WriteEndElement();
            }

Solution

  • This is not likely going to work, as XmlDocument and XmlNode, and all of the related types, are not thread safe. Trying to parallelize the writing will likely cause problems.