Question

So I am trying to lock an isolated storage file in my C# client application, so that multiple copies of my application are not able to access it at the same time. I am using the following syntax:

lockStream = new IsolatedStorageFileStream("my.lck", FileMode.OpenOrCreate, isoStore);
lockStream.Lock(0, 0);

This code causes my application to throw a NullReferenceException from inside the FileStream.Lock method of the framework. I have tried using a non-zero value for the length. I have tried writing a byte to the file and then locking just that byte. No matter what I do, that same NullReferenceException keeps plaguing me. Does anyone know if this is possible with isolated storage?

Also I am looking into using this technique in a Silverlight application as well, does Silverlight support file locking? The MSDN docs seem to indicate that it does not, but I have seen this post from a C# MVP that says it does.

Update: Microsoft has fixed the bug I submitted on Connect, but it was not released in version 4 of the framework. It should be available hopefully in the next SP or full release.

Was it helpful?

Solution

This looks like a bug in the Framework. I may be wrong, because it is really too big to be true.

Looking at the source code of .NET 3.5 SP1 with Reflector, one finds the IsolatedStorageFileStream calls the parameterless base constructor (FileStream()), which results in an not-really-initialized base class. IsolatedStorageFileStream creates an instance of a FileStream and uses it in all methods that it overrides (Write, Read, Flush, Seek, etc.). It is strange that it does not take advantage of its base class directly.

But Lock and Unlock are not overridden and they need a private field (_handle) that is still null (because the constructor used is the parameterless one). They assume it is non-null and dereference it and cause the NRE.

To summarize, Lock and Unlock are not supported (or buggy).

I guess you're forced to use other lock methods like a Mutex or Semaphore.

The implementation is the same in .NET 4 RC. In Silverlight, Lock an Unlock are not present at all (my apologies for contradicting an MVP).

OTHER TIPS

Try having a value greater than 0 for the amount of data to lock. Also, is there any data in the stream, if there is nothing to lock that might be the problem....

 lockStream = new IsolatedStorageFileStream("my.lck", FileMode.OpenOrCreate, isoStore);
 lockStream.Write(.....)
 lockStream.Lock(0, 10);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top