"Process/thread cannot access file" problem

G

Guest

Hi

Im trying to make an app that uses threading, I want to write to a file in a
loop.

How can i ensure that only one thread writes to the file a the time???

Im accessing the fil with:

Dim xFile As StreamWriter
xFile = New StreamWriter("C:\threadtest.txt", True, System.Text.Encoding.UTF8)
xFile.Write(Now)
xFile.Flush()
xFile.Close()

The error:
An unhandled exception of type 'System.IO.IOException' occurred in
mscorlib.dll
Additional information: The process cannot access the file
"C:\threadtest.txt" because it is being used by another process.
 
S

Sunny

Hi

Im trying to make an app that uses threading, I want to write to a file in a
loop.

How can i ensure that only one thread writes to the file a the time???

Im accessing the fil with:

Dim xFile As StreamWriter
xFile = New StreamWriter("C:\threadtest.txt", True, System.Text.Encoding.UTF8)
xFile.Write(Now)
xFile.Flush()
xFile.Close()

The error:
An unhandled exception of type 'System.IO.IOException' occurred in
mscorlib.dll
Additional information: The process cannot access the file
"C:\threadtest.txt" because it is being used by another process.


In C# there is lock() keyword. I do not know the equivalent in VB.Net,
but actually lock is just a syntax sugar for Monitor.Enter and
Monitor.Exit. The real code is something like:

monitor.Enter();
try
{
do my job
}
finally
{
monitor.Exit
}

I know that in VB.New there is a similar construct for
try/catch/finally, so if there is not a lock equivalent, you can do it
with something like that.

Sunny
 

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