开发者

File.Create seems to lock the file. How can I avoid this?

I have 2 threads that communicate by sending files to each other. When Thread #1 does a

// Thread #1
File.Create(@"C:\somedir\response.done");

Then Thread #2 is supposed to delete it.

// Thread #2
while (!File.Exists(@"C:\somedir\response.done"))
    Thread.Sleep(100);


while (File.E开发者_Go百科xists(@"C:\somedir\response.done"))
    {
        try {
               File.Delete(@"C:\somedir\response.done");
            }
        catch { Thread.Sleep(1000); };

    }

However, the file seems to be locked. There is generated a response.done file in the directory, but it is never deleted. When I try to manually remove it, then

"The action cannot be completed because the file is open in MyProgram. Close the file and try again."

How can I avoid this?


File.Create returns a FileStream. So... close it:

using(File.Create(path)) {
    // add contents here if needed
}

The using ensures it is Dispose()d, hence closed. Note: it is also possible that some AV systems will interfere with file access, but that is usually not a huge problem.


You need to close FileStream created by File.Create(@"C:\somedir\response.done");.


You can also use .Close()

So your code would become

// Thread #1
File.Create(@"C:\somedir\response.done").Close();


change your code to

// Thread #1
using (FileStream FS = File.Create(@"C:\somedir\response.done") ) {};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜