线程安全访问文本文件. [英] Thread-safe acces to a text file.

查看:79
本文介绍了线程安全访问文本文件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获得对文本文件的线程安全访问.

我是Threading的新手,我尝试了许多不同的解决方案,但我仍然没有任何成功.

我以为我可以创建一个类,并说:ThreadSafeFileInstance.

在这个课程中,我将有一个全局私有文件变量...

I need to gain thread-safe access to a Text-file.

I''m kinda new to Threading and I''ve tried many different solutions, but I''m still not having any success.

I thought I might Create a Class and call it say: ThreadSafeFileInstance.

In this class I''ll have a Global private File Variable...

private File _file;


我只能通过属性访问...


which I only give access to through a Property...

public File File
{
   get
   {
      return _file;                
   }
}



我以为可以使用Mutex对文件实例进行签出",如下所示:



I thought I could use Mutex to do a "check-out" of the File Instance like this:

public File File
{
   get
   { 
      myMutex.WaitOne();
      return _file;    
      myMutex.ReleaseMutex(); 
   }
}



但这显然不起作用,因为在Mutex释放属性后,调用该属性的对象仍将具有该文件的实例.

互斥锁会阻止方法中的代码,我需要一些可以阻止使用对象并导致其他线程在访问它并被锁定时等待的东西.

此类将扩展为包含所有基本的文件编辑方法,例如Read,Write,Replace等.我真的不确定如何在这种情况下使用Mutex.

您可能会推荐任何初学者文章?感谢任何建议.



But this obviously wouldn''t work, since the object calling the property will still have an instance of this file after the Mutex release the property.

Mutex blocks code in a method, I need something that can block the use of an object and cause other threads to wait when they access it and it''s locked.

This class will be extended to contain all the basic File-editing methods like Read, Write, Replace etc... I''m really not sure how to use Mutex in this context.

Any beginners article you might recommend? Any advice is appreciated.

推荐答案

如果您想为非线程安全的对象创建线程安全的包装,那么通常公开一个不安全的对象是一个坏主意.包装器中的非线程安全对象.一旦您暴露了它们,就很难确保消费者以线程安全的方式使用它们,这违背了包装器类的目的.不必公开原始的File对象,而是将线程安全的方法添加到ThreadSafeFileInstance类中,该方法对使用者类执行线程安全的操作.示例:您想将File包裹在ThreadSafeFileInstance中,因此您应从以下内容开始:
If you want to make a thread safe wrapper for a non-thread safe object then it''s generally a bad idea to expose the non-thread safe object from the wrapper. Once you''ve exposed them it''s very difficult to ensure that consumers use them in a thread safe way which defeats the purpose of the wrapper class. Instead of exposing the raw File object(s), add thread safe methods to the ThreadSafeFileInstance class that perform the thread safe operations for consumer classes. Example: you''d like to wrap a File in ThreadSafeFileInstance so you start with this:
internal sealed class ThreadSafeFileInstance
{
    // used to synchronize access to the file
    private readonly object _fileLock = new object();
    // initialize elsewhere
    private FileStream _file;
}



如果通过属性公开FileStream,则还必须公开锁对象,以便使用者可以在其上进行同步,但是无法保证他们确实在执行此操作.另一种方法是提供单独的GetHandleReleaseHandle方法,但是再次要强制正确使用这些方法很困难.如果类调用GetHandle然后忘记调用ReleaseHandle怎么办?

而是提供执行线程安全操作的方法:



If you expose the FileStream through a property then you also have to expose the lock object so that consumers can synchronize on it, but there''s no way to guarantee that they actually do it. An alternative way would be to provide separate GetHandle, ReleaseHandle methods, but again it''s difficult to enforce proper usage of those methods. What if a class calls GetHandle and then forgets to call ReleaseHandle?

Instead, provide methods that do thread safe operations:

internal sealed class ThreadSafeFileInstance
{
    // used to synchronize access to the file
    private readonly object _fileLock = new object();
    // initialize elsewhere
    private FileStream _file;
    internal void Append(string data)
    {
        lock (_fileLock)
        {
            // inside the lock use _file
            _file.Write(Encoding.ASCII.GetBytes(data), 0, data.Length);
        }
    }
    // etc.
}




就像Arun Jacob所说的那样,除非您绝对需要使用Mutex es,否则请使用lock(内部使用Monitor s)而不是使用Mutex es.为了保护单个应用程序内的单个资源,Mutex是过大的.




Also like Arun Jacob said, use a lock (which internally uses Monitors) instead of using Mutexes unless you absolutely need to use Mutexes. For protecting single resource inside of a single application a Mutex is overkill.


为此目的创建一个静态类.在该类中创建一个对象,然后在访问文件时使用锁,

Create a static class for this purpose. Create an object inside that class and while accessing file, use lock,

lock(obj)
{
   // Do work here
}



或使用Monitor类.

锁定C# [



or use Monitor class.

lock in C#[^]


互斥体的发布应该是一个单独的调用.上面显示的对象上的锁无助于防止这种情况.

类似的东西:
The release of the Mutex should be a separate call. The lock on an object as shown above won''t help prevent this.

something like:
File GetFileHandle()
{
 myMutex.WaitOne();      
 return _file;      
}

void ReleaseFile()
{
 myMutex.ReleaseMutex(); 
}



消费者应同时呼叫两者,例如:



a consumer should call both, like:

File f = GetFileHandle();
DoWork(f);
ReleaseFile();



为了使其更加安全,您可以关闭并重新打开文件,以确保赋予使用者的句柄无效.

祝你好运!



To make it even more safe you could close and reopen the file to make sure the handle given to the consumer is rendered invalid.

Good luck!


这篇关于线程安全访问文本文件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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