locked
Problem with Windows::Storage::FileIO::AppendTextAsync

    Question

  • Hi, dear all,

    Currently I encountered an issue with this function with the following error when I tried to write some logs into a file with Windows::Storage::FileIO::AppendTextAsync:

    "The process cannot access the file because it is being used by another process."

    Yeah, there is several thread, and I didn't wait for the previous append action when the next append is triggered.

    I ever asked a question (http://social.msdn.microsoft.com/Forums/windowsapps/en-US/6435e117-351a-4b96-8583-cd5587d1da2b/is-windowsstoragefileioappendtextasync-thread-safe) and Rob confirmed that this function is thread safe.

    Does it mean that I have to wait for the previous append to complete before the next append action?

    Thank you very much.

    Friday, July 5, 2013 3:48 AM

Answers

  • Thread safety just means that you can work with the object from multiple threads (i.e. you don't need to restrict use of it to the same thread). It doesn't mean that you are free and clear of the need to properly synchronize access to the object. If thread A starts doing something with the object then thread B swoops in and tries to do something while thread A is still doing its thing, chances are very good that things will go wrong. If you're lucky, it will crash. If not then you will get some unknown behavior.

    I think you've mentally tied together the concepts of thread safety and atomicity. An atomic operation is one that is guaranteed to run to completion before any other operation on the same data could have the chance to start. Atomicity is rare and usually requires the use of special types and corresponding functions (e.g. things from the <atomic> header from the C++ Standard Library).

    The answer to your question is yes you will need to wait for each append to complete before beginning a new one since it's not an atomic operation. The best way to accomplish this is to either use a synchronization mechanism (e.g. an SRWLOCK or a CRITICAL_SECTION) or else to ensure that you only access the object serially from a single thread.


    Visual C++ MVP | Website | Blog | @mikebmcl | Windows Store DirectX Game Template

    Saturday, July 6, 2013 6:43 AM