在新线程中打开 XML 文件?
您好,我遇到了一些麻烦,我想知道如何在新线程中读取 XML 文件,这基本上是我想要做的:
//This is ran when the user presses the Enter Key
Thread LoadThread = new Thread(new ThreadStart(Test));
LoadThread.Start();
private static void Test()
{
FileStream stream = File.Open("TEST_1.xml", FileMode.Open);
//----
// Code Using File (I know this stuff works)
//----
stream.Close();
}
这是错误。
Directory\TEST_1.xml',因为它正在被另一个进程使用。
但是当它不是自己的线程时它工作正常吗?
感谢您的帮助,如果不能这样做,我怎样才能打开文件而不使我的程序冻结直到文件被打开?
再次感谢。
Hi I'm Having some trouble, i was wonder how to read an XML file in a new thread heres basically what I'm trying to do:
//This is ran when the user presses the Enter Key
Thread LoadThread = new Thread(new ThreadStart(Test));
LoadThread.Start();
private static void Test()
{
FileStream stream = File.Open("TEST_1.xml", FileMode.Open);
//----
// Code Using File (I know this stuff works)
//----
stream.Close();
}
Here's the Error.
Directory\TEST_1.xml' because it is being used by another process.
But when its not a thread of its own it works fine ?
Thanks for the help, if this can't be done like this, how can i open the file without it making my program Freeze until the file has been opened ?
thanks again.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我拿了你的示例代码,没有遇到任何问题。然而,当我在读取文件时按下回车键时,我确实遇到了同样的异常。 (即按回车键两次)是否可能有两个回车键处理程序,它们都触发打开该文件。您可以在 File.Open 语句上放置一个断点,看看在异常发生之前它被击中了多少次。
I took your sample code and did not run into any problems. I did, however, get the same exception when I pressed the enter key while the file was being read. (i.e. pressed the enter key twice) Is it possible you have two handlers for the Enter key, which are both triggering this file to be opened. Can you place a breakpoint on the File.Open statement and see how many times it is hit before the exception occurs.
您是否有正在写入文件的代码或进程?如果是这样,您需要进行一些锁定:
Do you have code or a process that is writing to the file? If so, you'll need to do some locking: