use ReaderWriterLock in c# xaml

67 Views Asked by At

I want to use ReaderWriterLock in this function:

    static async void ETDGazeDataEvent(ETMWNet.ETGazeDataType pGazeData)
    {
        StorageFolder ETfolder = ApplicationData.Current.LocalFolder;
        StorageFile file = await ETfolder.CreateFileAsync("Log.ETDGazeDataEvent.txt", CreationCollisionOption.OpenIfExists);
        String ETAnswer = pGazeData.FrameNum + " Time: " + pGazeData.TimeStamp + " X: " + pGazeData.Left.GazePointPixels.x + " Y: " + pGazeData.Left.GazePointPixels.y + " \r\n";
        await Windows.Storage.FileIO.AppendTextAsync(file, ETAnswer);
    }

This function called 30 times in second, and each time the function write data to text file. I want to add code that lock the function until it finish to write the sampled data every time. which code I need to add so it work well on vs2013 c# xaml?

1

There are 1 best solutions below

0
On

I want to add code that lock the function until it finish to write the sampled data every time.

What you really want is ordered execution, not just mutual exclusion. So, a ReaderWriterLock (or any other mutual exclusion primitive) is the wrong solution. However, a queue would work fine.

There aren't too many async-ready queues around, but TPL Dataflow has a nice one called ActionBlock. You can use it like this:

private static readonly ActionBlock<ETMWNet.ETGazeDataType> _queue = new ActionBlock<ETMWNet.ETGazeDataType>(
  async pGazeData =>
  {
    StorageFolder ETfolder = ApplicationData.Current.LocalFolder;
    StorageFile file = await ETfolder.CreateFileAsync("Log.ETDGazeDataEvent.txt", CreationCollisionOption.OpenIfExists);
    String ETAnswer = pGazeData.FrameNum + " Time: " + pGazeData.TimeStamp + " X: " + pGazeData.Left.GazePointPixels.x + " Y: " + pGazeData.Left.GazePointPixels.y + " \r\n";
    await Windows.Storage.FileIO.AppendTextAsync(file, ETAnswer);
  });

static void ETDGazeDataEvent(ETMWNet.ETGazeDataType pGazeData)
{
  _queue.Post(pGazeData);
}