读写xml文件的并发量很大,大家是怎么解决的
发布网友
发布时间:2022-04-07 20:28
我来回答
共3个回答
懂视网
时间:2022-04-08 00:50
FileAccess枚举
标签:
热心网友
时间:2022-04-07 21:58
测试方法:开两个线程读写同一个文件。主要是FileStream对象里面的三个参数FileMode,FileAccess,FileShared的枚举值选择。
class Program
{
private static string path = AppDomain.CurrentDomain.BaseDirectory + "cache.xml";
static void Main(string[] args)
{
Thread th1 = new Thread(Writexml);
th1.Start();
Thread th2 = new Thread(Readxml);
th2.Start();
}
static void Writexml()
{
while (true)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(String.Format("<Cache name=\"{0}\">", "aa"));
sb.AppendLine(String.Format("<Subkey name=\"{0}\">", "bb"));
sb.AppendLine(String.Format("<Data><![CDATA[{0}]]></Data>", "{\"Value\":[{\"BindingType\":\"net.tcp\",\"ServiceIP\":\"192.168.1.226\",\"ServicePort\":\"9420\",\"SvcPath\":\"HotelPayNotifyService.svc\"}]}"));
sb.AppendLine("</Subkey>");
sb.AppendLine("</Cache>");
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
fs.Write(bytes, 0, bytes.Length);
}
Thread.Sleep(200);
}
}
static void Readxml()
{
while (true)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
XmlDocument doc = new XmlDocument();
doc.Load(fs);
XmlNode dataNode = doc.SelectSingleNode(String.Format("Cache/Subkey[@name='{0}']/Data", "bb"));
Console.WriteLine(dataNode.InnerText);
}
Thread.Sleep(100);
}
}
}
这样的情况还是比较正常,在几百毫秒的情况下,这样的能够满足大部分要求了。
另:还遇到了关于Dictionary并发的问题,声明了一个静态的Dictionary对象,通过深度复制来保证并发读写不会抛异常。处理的代码如下:
Dictionary<String, Dictionary<String,
Object>> newdic = new Dictionary<string, Dictionary<string,
object>>();
using (MemoryStream ms = new MemoryStream())
{
IFormatter formator = new BinaryFormatter();
formator.Serialize(ms, dic);
ms.Seek(0, SeekOrigin.Begin);
newdic=(formator.Deserialize(ms) as Dictionary<String,Dictionary<String,Object>>);
}
热心网友
时间:2022-04-07 23:16
提升磁盘性能,服务器的话,上企业级固态,或者用固态做阵列,来获取高iops。