2012-06-12 19 views
0

我是网络编程的新手(Visual Web Developer中的C#),我的非C编程技能也有点生疏。意外创建多个进程

我创建了一个表格,其中一些单元格提示用户输入,一旦给出输入,输入将替换提示。因此,表格只能由第一人注解来访问该页面。稍后,注释页面需要提供给其他人查看,因此我需要页面在第一次完成后没有提示的情况下加载。为此,我(尝试)识别用户,以便该用户获得可编辑页面,将所有编辑保存到xml文件中,并且如果有其他用户运行该页面,表格设置会从xml文件中读回的编辑。

我无法一直写入xml文件。具体来说,我似乎有时会创建多个访问该文件的进程,并在我的代码尝试更新时抛出运行时异常。

因为我不想在每个页面加载时创建一个新文件,所以我认为静态类是最好的选择。下面是代码:

static class XMLReaderWriter 
{ 
    static String fileLocation = "D:\\WebApp\\dashboard.xml"; 
    static XMLReaderWriter() 
    { 
     FileStream fs = File.Create(fileLocation); 
     if (File.Exists(fileLocation)) 
     { 
      // The opening tag 
      writeToFile(fileLocation, "<Dashboard>\n"); 
     } 
     else 
     { 
      Exception e = new Exception("Failed to create " + fileLocation); 
      throw e; 
     } 
    } 
    public static void writeXML(String xml) 
    { 
     if(File.Exists(fileLocation)) 
     { 
      writeToFile(fileLocation, xml); 
     } 
     else 
     { 
      File.Create(fileLocation); 
      writeToFile(fileLocation, xml); 
     } 
    } 

    private static void writeToFile(String fileLocation, String xml) 
    { 
     StreamWriter sw = new StreamWriter(fileLocation, true); 
     sw.WriteLine(xml); 
     sw.Close(); 
     sw.Dispose(); 
    } 

    public static string readXML(String trendID) 
    { 
     StringBuilder result = new StringBuilder(""); 
     if (File.Exists(fileLocation)) 
     { 
      XDocument xDoc = XDocument.Load(fileLocation); 
      var image = from id in xDoc.Descendants(trendID) select new 
         { 
          source = id.Attribute("image").Value 
         }; 
      foreach (var imageSource in image) 
      { 
       result.AppendLine(imageSource.source); 
      } 
     } 
     return result.ToString(); 
    } 

    public static void done() 
    { 
     // The closing tag 
     writeToFile(fileLocation, "</Dashboard>"); 
    } 
} 

和这里是我打电话的方法:

XMLReaderWriter.writeXML("\t<trend id=\"" + trendID +"\">\n\t\t" + innerHTML + "\" />\n\t</trend>"); 

终于有一个提交按钮,关闭标签添加到XML文件:

<asp:Button runat="server" Text="Submit Changes" OnClick="Submit_Click" /> 

protected void Submit_Click(Object sender, EventArgs e) 
{ 
    XMLReaderWriter.done(); 
} 

有时一切正常 - 虽然我似乎生产格式不正确的XML。但大多数情况下,我得到多个进程访问xml文件。

任何意见表示赞赏。

问候。

回答

1

Web编程意味着在多线程环境中工作。

从浏览器到Web服务器的每个请求是一个单独的线程

这就是为什么有时候你的文件不能被访问,因为其他请求(比如线程)有可能被独占锁定。

的另一点是using语句应该是你的朋友,所以更换:

StreamWriter sw = new StreamWriter(fileLocation, true); 
sw.WriteLine(xml); 
sw.Close(); 
sw.Dispose(); 

...有:

using(StreamWriter sw = new StreamWriter(fileLocation, true)) 
{ 
    sw.WriteLine(xml); 
} 

这是一个相当于试,终于块并且对IDisposable的任何实现调用Dispose方法。因此,如果您的区块失败,则始终致电Dispose()

而且上述评论它的罚款一提的是,如果在某个线程的东西有些操作过程中出了问题,一个锁文件将保留在它永远,直到IIS应用程序停止或应用程序池得到回收。

摘要:

  1. 在你的情况,多线程可能试图写入到同一个文件。
  2. 某些错误可能会在受影响的文件中留下一些锁定。

解决方案:不要使用Web应用程序中的文件,有更好的方法来保存数据:数据库 - 这些解决了并发场景中的很多问题! -

+0

啊谢谢。我没有意识到每个页面请求都是一个单独的线程。这解释了一切。 – Kevin