I have application which has several threads. First thread writes into the StorageFile
, second thread reads from the same StorageFile
. Problem is, I can't prevent second thread from reading that file, while first thread is writing into it. Is here something like Using
keyword I can use for getting single access to the file?
There is similar question on StackOverflow, but it doesn't suite to my solution.
My code:
public async static Task<bool> Save(string filename, object o)
{
try
{
Stream stream;
var folder = Windows.Storage.ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
stream = await file.OpenStreamForWriteAsync();
if (o == null || stream == null)
{ }
else
{
DataContractSerializer ser = new DataContractSerializer(o.GetType());
ser.WriteObject(stream, o);
}
return true;
}
catch (Exception e)
{
return false;
}
}
I finally solved the problem by adding lock on the data in the memory, not on the file, which would be time-consuming, though elegant. However, during finding solutions in reaction to Srirama Sakthivel's hint I found this very useful topic. I hope that will help someone.