Exclusive Writes to a file.

L

L

Hi,

If two applications try to write to the same file at the same time,
an exception gets thrown. How can we handle exclusive writes to a file?

Thanks,
Lalasa.
 
O

Olaf Baeyens

If two applications try to write to the same file at the same time,
an exception gets thrown. How can we handle exclusive writes to a file?
This is an art on its self.

Best is to do retries with a randomized interval.
For example try to open the file with 10 retries but wait about 0.5 second
between each trial of opening.
But this means that the time of the open and close of that file should be
less that 5 seconds. Otherwise the other application will fail if it cannot
open in 5 seconds. One solution to speed up is to prepare the data before
you are going to write in a memory block and transfer the complete block in
one pass.

An alternative way is record locking.
 
L

L

Hi Olaf

How do I program opening a file with retries? Can you please put
some sample code that describes it?

How can Record locking be used when opening a file for write? A sample
code will help.

Thanks,
Lalasa.
 
O

Olaf Baeyens

How do I program opening a file with retries? Can you please put
some sample code that describes it?
Right now I do not have the time to give any code but it would look
something like this;

bool bOpened=false;
for (int iTries=0; iTries<10; iTries++) {
bOpened =OpenFile()
if (bOpened ) break;
Sleep(1000); // 1 second
}
if (bOpened ) {
--> Do your stuff
CloseFile();
} else {
--> generate error
}
How can Record locking be used when opening a file for write? A sample
code will help.
I do not have experience with .NET at this moment.

Basically you open the file and then lock a range of bytes you are going to
read/write , so if another program wants to access that region, then they
get an error. But the other program is free to change the bytes outside that
locked region.
After the process you unlock that region and close the file.
 

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