0

我在具有相同 xmlRequestPath 和 xmlResponsePath 文件的循环中调用以下方法。两次循环计数它在第三次迭代中执行良好我收到异常“该进程无法访问该文件,因为它正在被另一个进程使用。”。

    public static void UpdateBatchID(String xmlRequestPath, String xmlResponsePath)
    {
        String batchId = "";
        XDocument requestDoc = null;
        XDocument responseDoc = null;
        lock (locker)
        {
            using (var sr = new StreamReader(xmlRequestPath))
            {
                requestDoc = XDocument.Load(sr);
                var element = requestDoc.Root;
                batchId = element.Attribute("BatchID").Value;

                if (batchId.Length >= 16)
                {
                    batchId = batchId.Remove(0, 16).Insert(0, DateTime.Now.ToString("yyyyMMddHHmmssff"));
                }
                else if (batchId != "") { batchId = DateTime.Now.ToString("yyyyMMddHHmmssff"); }
                element.SetAttributeValue("BatchID", batchId);
            }

            using (var sw = new StreamWriter(xmlRequestPath))
            {
                requestDoc.Save(sw);
            }

            using (var sr = new StreamReader(xmlResponsePath))
            {
                responseDoc = XDocument.Load(sr);
                var elementResponse = responseDoc.Root;
                elementResponse.SetAttributeValue("BatchID", batchId);

            }

            using (var sw = new StreamWriter(xmlResponsePath))
            {                    
                responseDoc.Save(sw);                    
            }
        }
        Thread.Sleep(500);

        requestDoc = null;
        responseDoc = null;
    }

异常发生using (var sw = new StreamWriter(xmlResponsePath))在上面的代码中。

例外:

The process cannot access the file 'D:\Projects\ESELServer20130902\trunk\Testing\ESL Server Testing\ESLServerTesting\ESLServerTesting\TestData\Assign\Expected Response\Assign5kMACResponse.xml' because it is being used by another process.

4

2 回答 2

0

也许在第三个循环中,流仍然被关闭,所以它告诉你它是不可访问的。尝试在循环中再次调用之前稍等片刻,例如:

while (...)
{
    UpdateBatchID(xmlRequestPath, xmlResponsePath);
    System.Threading.Thread.Sleep(500);
}

或者,显式关闭流,而不是将工作留给垃圾收集器:

var sr = new StreamReader(xmlResponsePath);
responseDoc = XDocument.Load(sr);
     ....
sr.Close();
于 2014-06-24T12:39:18.667 回答
0

不要使用两个流,一个写入流和一个读取流,而是尝试只使用一个 FileStream,因为问题可能是在加载文件后,流保持打开状态,直到垃圾收集器激活。

using (FileSteam f = new FileStream(xmlResponsePath))
{
     responseDoc = XDocument.Load(sr);

     var elementResponse = responseDoc.Root;
     elementResponse.SetAttributeValue("BatchID", batchId);

     responseDoc.Save(sw);                    
}
于 2014-06-24T12:49:40.307 回答