File Locking


J

Jan Hudecek

Hello group,

I have two processes which are using a shared resource on a Windows
Mobile 6.1 and .NET 3.5. I have decided that the easiest way to
synchronize the access is to use a lock file and two methods:

internal static void Unlock(string lockfile)
{
if (File.Exists(lockfile))
File.Delete(lockfile);
}

internal static void Lock(string lockfile)
{
string lockname = lockfile;
while (true)
try
{
new FileStream(lockname, FileMode.CreateNew).Close
();
return;
}
catch (IOException ex)
{
Thread.Sleep(100);
}
}

But Im getting IOException on File.Delete in Unlock sometimes. Is it
possible that CreateFile with CreateNew actualy DOES open the file if
it exists thus locking it and preventing the other process from
deleting it?
Or would anybody recommend me a better way to achieve the
synchronization?

Thanks,
Jan
 
Ad

Advertisements

D

DrewCE

A Named Mutex, I think, is what you should be looking for but it's not
included in the Compact Framework. It needs to be P/Invoked. The OpenNetCF
SDF includes an implementation you could use.

Here's a description of the full framework usage...
http://msdn.microsoft.com/en-us/library/f55ddskf(VS.80).aspx

Using a file to synchronize threads in different processes is just asking
for trouble, IMHO.

-Drew
 

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