FileSystemWatcher和Task正在由另一个进程使用文件

Gra*_*ter 6 c# multithreading filesystemwatcher task

我创建了一个应用程序,它只会查看新创建的文件的某个文件夹并将其列在列表框中,现在我想要做的是每当它检测到应用程序将读取它的文件并在列表框中显示文本时,我几乎得到了,因为有时当它检测到2或3,4,5,6等文件时有时可以正常但有时也会提示错误"进程无法访问文件'C:\ Users\PHWS13\Desktop\7.request.xml '因为它被另一个进程使用了​​."

如何解决这个问题?这是我的代码:

private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        if (!listBox1.Items.Contains(e.FullPath))
        {
            //add path
            listBox1.Items.Add(e.FullPath + "" + DateTime.Now.ToString());
            //get the path
            path = e.FullPath;
            //start task
            startTask();
        }
    }

    private void startTask()
    {
        //start task
        Task t = Task.Factory.StartNew(runThis);
    }

    private void runThis()
    {
        //get the path
        string get_the_path = path;

        XDocument doc = XDocument.Load(get_the_path);
        var transac = from r in doc.Descendants("Transaction")
                      select new {
                          InvoiceNumber = r.Element("InvoiceNumber").Value,
                      };
        listBox2.Invoke((MethodInvoker)delegate() { 
            foreach(var r in transac){
                listBox2.Items.Add(r.ToString());
            }
        });
Run Code Online (Sandbox Code Playgroud)

max*_*mpa 4

尝试使用XDocument.Load(Stream)只读选项:

using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read)) 
{
    var doc = XDocument.Load(stream);

    // ...
}
Run Code Online (Sandbox Code Playgroud)