无法使用lock()或Mutex

时间:2016-12-29 06:52:33

标签: multithreading parallel-processing locking mutex

我正在编写一个简单的应用程序,它从多个线程写入大约1000次迭代的单个xml文件。 我尝试使用lock(),Mutex和ReaderWriterSlim来锁定文件。它工作了一段时间但是给出了另一个进程正在访问该文件的错误。 有人可以帮我解决一下:

或者还有其他方法可以实现这一目标。

public class XmlWrite
{
    //private static object _lock = new Object();


    static string xmlFilePath = "C:\\Test\\Multi.xml";
    public static Mutex m_Mutex = new Mutex(false, @"Global\MyMutex");

    public static void LogXML(object threadID)
    {
        int i = 0;
        while (i < 1000)
        {
            try
            {
                m_Mutex.WaitOne();
                XmlDocument xml = LoadDocument(xmlFilePath);

                var xmlElement = XElement.Load(new XmlNodeReader(xml));

                var sourceXElement = new XElement("ParentNode");
                sourceXElement.Add(new XElement("ChildNode", threadID));

                xmlElement.Add(sourceXElement);

                SaveDocument(xmlElement, xmlFilePath);

                Console.WriteLine("Value " + xml.ToString() + "Index" + i + "Thread" + threadID.ToString());
            }
            catch (Exception exe)
            {
                Console.WriteLine(exe.Message);
            }
            finally
            {
                m_Mutex.ReleaseMutex();
            }
            i = i + 1;
        }
    }

    public static XmlDocument LoadDocument(String path)
    {
        XmlDocument document = new XmlDocument();
        using (StreamReader stream = new StreamReader(path, Encoding.GetEncoding("iso-8859-7")))
        {
            document.Load(stream);

        }
        return (document);
    }

    public static XElement SaveDocument(XElement document, String path)
    {
        using (StreamWriter stream = new StreamWriter(path, false, Encoding.GetEncoding("iso-8859-7")))
        {
            document.Save(stream);
        }
        return (document);
    }


}


class Program
{
    static void Main(string[] args)
    {


        new Thread(XmlWrite.LogXML).Start("A");
        new Thread(XmlWrite.LogXML).Start("B");
        new Thread(XmlWrite.LogXML).Start("C");
        new Thread(XmlWrite.LogXML).Start("D");
        new Thread(XmlWrite.LogXML).Start("E");
        new Thread(XmlWrite.LogXML).Start("F");
        new Thread(XmlWrite.LogXML).Start("G");
        new Thread(XmlWrite.LogXML).Start("H");
        new Thread(XmlWrite.LogXML).Start("i");
    }
}

0 个答案:

没有答案