最近我在写asp.net程序时遇到了一个同步问题,多人同时打开文件流写xml文件时系统出现一些莫名其妙的问题,代码如下:
.......
private void Submit_Clicked(object sender, System.EventArgs e)
{
str=TextBox1.Text;
XmlDocument doc=new XmlDocument();

for(int i=0;i<10;i++)
{

try
{
FileStream fs=new FileStream(@"C:\Inetpub\wwwroot\testConcurrent\test.xml",FileMode.Open,FileAccess.ReadWrite); doc.Load(fs);//调试过程中第一个进入者运行到该行后,第二个进入者点击提交按钮提交触发该事件,此时程序直接跳转到函数开头开始运行,导致打开文件流时出错

XmlNode node1=doc.DocumentElement.FirstChild.Clone();
node1.FirstChild.InnerText=str;
doc.DocumentElement.AppendChild(node1);

doc.Save(fs); Response.Write(@"<script>window.document.location.href='tt.aspx'</script>;");
fs.Close();
break;
}

catch (Exception ex)
{
string ss=ex.Message;
Thread.Sleep(1000);
} }
该代码处理提交后在textbox控件中的输入内容,并将其写入xmlnode中并存入xml文件,本来我准备通过控制该线程休眠来解决同时打开文件流时一部分信息丢失的问题,但结果并不算理想,希望高手能指点迷津!