Search code examples
c#multithreadingmicrosoft-metrostoragefile

Metro StorageFile Multithreaded File logging


What is the correct way for handling multithreaded file access to the StorageFile object?

After creating a StorageFile, I write to it using FileIO.AppendTextAsync.

This works, but as soon as multiple threads call FileIO.AppendTextAsync, I get Access Denied errors - presumably because a previous call to it, is still running.

How do I deal with this situation?


Solution

  • I haven't found the perfect solution, but I have found a workable one.

    1. Mark the StorageFile with the volatile keyword (Significantly reduced errors).
    2. Then I refactored some code that was unnecessarily executing from different threads (Now all errors gone).

    NOTE: Both 1 and 2 implemented together were necessary to achieve the desired result - hence my comment about the solution NOT being perfect.

    UPDATED: For a more correct solution, please see this post: FileIO Multiple Threads