Lock()

G

Guest

Ok, so I have one program that has locked a file while it is being written to
disk.

lock (typeof(StreamWriter))
{
using (StreamWriter sw = new StreamWriter("C:\\Test\\filename.txt"))
{
sw.WriteLine("test text");
sw.Close();
}
}

Now, I have another program that is trying to access the same file
(filename.txt).

using (StreamReader sr = new StreamReader("C:\\Test\\filename.txt"))
{
sr.ReadLine("test text");
sr.Close();
}

How can the second program test to see if the first program still has
(filename.txt) locked? I need the data in the second program before moving
to the next step.
 
E

Erick Sgarbi

1- If it is a dependent sequential process that you need... consider
wrapping the logic into items (abstract or interface based) and loading
them into a queue... then executing one by one while de-queuing the work
items as they finish.

2- Begin another thread to read the file and wait for the callback for
when the method returns (use ManualResetEvent to wait for the worker
thread).

I would use the 1st approach.


HTH
Erick Sgarbi
www.blog.csharpbox.com
 
D

Dmytro Lapshyn [MVP]

Hi,

The lock statement is not cross-process. You can open the file with sharing
disallowed, then no other process can open the file.
If you need advanced cross-process synchronization, consider a named mutex
or a named event (you might have to resort to using plain Win32 API to use
them).
 
J

Jon Skeet

Ok, so I have one program that has locked a file while it is being written to
disk.

lock (typeof(StreamWriter))
{
using (StreamWriter sw = new StreamWriter("C:\\Test\\filename.txt"))
{
sw.WriteLine("test text");
sw.Close();
}
}

That's not actually locked the file. That's locked the monitor for the type
of StreamWriter, which isn't generally a good idea - another thread could
lock the same type even though it isn't actually sharing any data. See
http://www.pobox.com/~skeet/csharp/threads/lockchoice.shtml for advice on
this matter.
Now, I have another program that is trying to access the same file
(filename.txt).

using (StreamReader sr = new StreamReader("C:\\Test\\filename.txt"))
{
sr.ReadLine("test text");
sr.Close();
}

How can the second program test to see if the first program still has
(filename.txt) locked? I need the data in the second program before moving
to the next step.

You need to use a Mutex. See
http://www.pobox.com/~skeet/csharp/threads/waithandles.shtml for more
information on them.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top