是否可以使用 PLINQ 写入 XmlWriter?还有其他流/作家吗?
我在每个阶段都使用 PLINQ,但生成 XML 输出。我尝试了一下,发现了一些奇怪的异常。所以我想知道是否有一个技巧可以让我进行异步输出。
...
[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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不太可能起作用,因为
XmlDocument
和XmlNode
以及所有相关类型都不是线程安全的。尝试并行写入可能会导致问题。This is not likely going to work, as
XmlDocument
andXmlNode
, and all of the related types, are not thread safe. Trying to parallelize the writing will likely cause problems.您可能正在寻找TPL 数据流。应该从单个线程写入文件,直到它关闭。 TPL 数据流允许轻松地将写入请求集中到同一线程上。
看起来您正在使用 WCF。例如,如果您的请求到达多个线程,并且您希望将它们记录到同一个文件中,则可以使用 TPL 数据流将它们汇集起来。
You're probably looking for TPL Dataflow. Should be writing to file from a single thread, until it's closed. TPL dataflow allows to easily funnel your write requests onto the same thread.
Looks like you're using WCF. If you have requests that arrive on multiple threads and you'd like to, for example, log them to the same file, you could use TPL Dataflow to funnel them in.