Identify if a file is being used by another thread

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a dll which is call by an ASP page, this dll has to perform read/write
operations on a file, I seem to be encountering the following error" Process
cannot access xyz.txt cause its held bby another process", is there any way I
can check if the file is being accessed by another process & if so I could
wait till that operation is done. If not is there a way I can make sure only
1 object of a class is created, the singleton approach wouldnt work as it
just allows tme to create one instance, in case of multithreaded applications
it fails.
 
Hi,

is there any way I
can check if the file is being accessed by another process & if so I could
wait till that operation is done.

No AFAIK, you can always wrap a try/catch to the open operation, if you get
an exception, then you know.

The wait part is easy, just do a loop around it ( you better use
Thread.Sleep() to give time to the other thread to finish )
now I do not know how wise this approach is in a web environment, remember
that if the browser does not gets a answer in a timeframe it will give you
error.
If not is there a way I can make sure only
1 object of a class is created, the singleton approach wouldnt work as it
just allows tme to create one instance, in case of multithreaded applications
it fails.

It does not fail, it create one instance for the entire application, are you
looking for one instance for each thread?
I don't know of any approach for this :(

cheers,
 
What I actually want is if one object is created for a class then no more
objects should be created. So from my web page when I try to instantita a new
object if one exists it should through me an error. Do you think a global
mutex would be able to identify if another instance is running.
 
I don't think that this is the best idea. A better way to do it would
be to call the CreateFile API directly, requesting the appropriate share
privledges.

When calling CreateFile, if the handle is invalid (-1), then you can
call the static GetLastWin32Error method on the Marshal class to get the
last error returned from GetLastError. In the case of a sharing violation,
that value is 32.

If there is no error, then the handle can be passed to the FileStream
class, and the class used as normal.

Hope this helps.
 
Nikhil,

I don't think you need a mutex, only have an exception thrown in the
constructor if the file is shared. This way, you will only ever have one
valid instance.

Also, you should make sure to implement the IDisposable interface on
your class, so that you close the handle as soon as possible.

Hope this helps.
 
Back
Top