prongs
prongs

Reputation: 9606

c# file read/write lock

I'm uring StreamReader to read/write from/to a file in two threads, read in one and write in other. I want that these two don't occur at the same time. What lock should I use? I looked at some examples but they were using FileStream.Lock and I'm not sure whether I can use that with StreamReader so please clarify.

Upvotes: 1

Views: 5672

Answers (3)

Darthg8r
Darthg8r

Reputation: 12675

In addition to locking the file itself, use the "lock" keyword. Otherwise, you will throw an exception when trying to work with a locked file

private object lockObject = new Object();

//  Code in thread that reads
lock(lockObject)
{
     // Open the file and do something
    // Be sure to close it when done.
}


// Somewhere else in another thread
lock(lockObject)
{
    // Open the file for writing and do somethign with it
    // Be sure to close it when done.
}

Upvotes: 1

Evert
Evert

Reputation: 8541

you could use a semaphore

http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx

Upvotes: 1

Didaxis
Didaxis

Reputation: 8736

You could create your own lock:

class Example
{
    private static readonly object SyncRoot = new object();

    void ReadOrWrite()
    {
        lock(SyncRoot)
        {
            // Perform a read or write
        }
    }
}

Upvotes: 0

Related Questions