Lock xml file writes through multiple aspx pages

V

vani

What is the best way to lock an xml file if there are multiple aspx pages
and/or ascx controls trying to write to it at the same time?
I already got a suggestion to use FileShare.None on a filestream that is
passed to XDocument, but I would prefer a solution that blocks/waits.
 
R

Registered User

Are all of these reads under your control? If so then a mutex based on the
file name might be one way - so you only attempt to open the file if you can
get the mutex. But obviously this won't work unless you can do this on every
page and control which is trying to access the page.

Create a type to hide the file itself. Public properties and methods
can be added to allow interaction with the file's data. When access is
needed to the file and its data, create an object of the type. The
sample below likely provides a better explanation of what I mean.

regards
A.G.

public class FileContainer
{
private static Mutex mutex = new Mutex();
internal string pathAndFileName;
public FileContainer(string pathAndFileName)
{
this.pathAndFileName = pathAndFileName;
load();
}

private void load()
{
if (File.Exists(pathAndFileName))
{
mutex.WaitOne();
try
{
// read file here
...
}
finally
{
mutex.ReleaseMutex();
}
}
}

private void save()
{
mutex.WaitOne();
try
{
// write file here
...
}
finally
{
mutex.ReleaseMutex();
}
}
// additional methods, members & properties
...
}
 
V

vani

Create a type to hide the file itself. Public properties and methods
can be added to allow interaction with the file's data. When access is
needed to the file and its data, create an object of the type. The
sample below likely provides a better explanation of what I mean.

regards
A.G.

public class FileContainer
{
private static Mutex mutex = new Mutex();
internal string pathAndFileName;
public FileContainer(string pathAndFileName)
{
this.pathAndFileName = pathAndFileName;
load();
}

private void load()
{
if (File.Exists(pathAndFileName))
{
mutex.WaitOne();
try
{
// read file here
...
}
finally
{
mutex.ReleaseMutex();
}
}
}

private void save()
{
mutex.WaitOne();
try
{
// write file here
...
}
finally
{
mutex.ReleaseMutex();
}
}
// additional methods, members & properties
...
}

Thanks for the kick, will try.
 

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

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top