http://msdn2.microsoft.com/zh-cn/library/system.io.textwriter.synchronized.aspx很多关于读写文本文件的源码示例都是用了这个静态方法包装进程,能不能解释下该方法的原理?比如当 a和b 两个线程同时读写那个xml文件时(已经包装过了),.net是怎么处理资源互斥的?

解决方案 »

  1.   

    to 比如当 a和b 两个线程同时读写那个xml文件时(已经包装过了),.net是怎么处理资源互斥的?Method1: use "lock" statement;
    sample code as follows
    lock( this )
    {
        // operation here
    }Method2: use "Mutex" class
    sample code as follows
    private Mutex mUnique = null;
    if( mUnique == null ) mUnique = new Mutex();
    mUnique.WaitOne();
    // operation here
    mUnique.ReleaseMutex();
      

  2.   

    读入一个数组
    FileStream xmlFile = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.Read);
    StreamReader xmlStream = new StreamReader(xmlFile, Encoding.UTF8);
    XmlTextReader xmlDoc = new XmlTextReader(xmlStream);
    .................写入文件
    FileStream xmlFile = new FileStream(url, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
    TextWriter textWriter = new StreamWriter(xmlFile, Encoding.UTF8);
    textWriter = TextWriter.Synchronized(textWriter);
    XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);我是这么写的,FileShare 设置成了 None,textWriter 加上了包装。因为这个xml文件的读写频率非常高,实际测试过程中出现了一些用户数据写入不全的问题。请问该如何提高读些性能?如果需要利用异步,能不能提供一个示例?
      

  3.   

    to 我是这么写的,FileShare 设置成了 None,textWriter 加上了包装。因为这个xml文件的读写频率非常高,实际测试过程中出现了一些用户数据写入不全的问题。请问该如何提高读些性能?可以把FileShare.None改为可以Read
      

  4.   

    to Knight94 能不能收下留言?