FileStream锁定文件以进行读写 [英] FileStream locking a file for reading and writing

查看:152
本文介绍了FileStream锁定文件以进行读写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码块让我很头疼.

I have the following code block which is giving me a headache.

从逻辑上讲,它应该可以正常工作,因为我正在使用在using语句中提供锁定的文件流.当到达创建StreamWriter的行时,它不会说文件不可写".

Logically it should work as I am using the filestream providing the lock within the using statement. When it gets to the line that creates the StreamWriter, it fails saying "the file is not writable".

现在我的程序是一个多线程应用程序.任何线程都可能试图写入该文件.我需要程序来锁定文件,读取内容,检查内容,然后写回所有更改.在该过程中,没有其他线程可以访问该文件.

Now my program is a multithreaded application. Any thread could be trying to write to this file. I need the program to lock the file, read the contents, check the contents, then write back any changes. During that process, no other thread should be able to access that file.

using (var fs = File.Open(fileLoc, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
    var sr = new StreamReader(fs);
    var str = sr.ReadToEnd();
    var strArray = str.Split(',');
    if (strArray.Any(st => st == text))
    {
        return;
    }
    sr.Close();

    var sw = new StreamWriter(fs);
    sw.Write(str + text);
    sw.Flush();
    sw.Close();
}

推荐答案

FileShare.None标志不会导致线程排队,它只会锁定文件,因此会导致异常.要提供互斥访问,可以在写入之前锁定共享对象.

The FileShare.None flag does not cause threads to queue, it just locks the file, hence the exception that you get. To provide mutually exclusive access you can lock a shared object prior to writing.

但是您说的是现在我的程序是一个多线程应用程序.任何线程都可能试图写入该文件."现在,这些线程是否都使用完全相同的方法写入文件?假设他们这样做了,那么这应该起作用...

But you say this "Now my program is a multithreaded application. Any thread could be trying to write to this file." Now, do these threads all use exactly the same method to write to the file? Let's assume they do, then this should work ...

创建一个静态类变量...

Create a static class variable ...

private static object lockObject = new object();

在这里使用...

lock (lockObject) 
{
    using(var sw = new StreamWriter(fs))
    {
       sw.Write(str + text);
    }
}

我对线程做了一些假设,因此,如果这不起作用,您可能必须查找有关同步的信息,或者向我们提供更多信息.

I have made some assumptions about the threads, so you may have to look up info on synchronization if this doesn't work or provide some more info to us.

此外,请更早关闭StreamReader(以防方法更早返回).使用后立即关闭它,或者最好使用using.

Also, please close your StreamReader earlier (in case the method returns earlier). Close it immediately after you use it or better yet use using.

这篇关于FileStream锁定文件以进行读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆