UnauthorizedAccessException C# File.IO Async

I had to upgrade one application and put some extra functionality. So i added an async function that handles a .txt file and edit some fields.

So i used this code


But i also had a function in MainPage that asynchronously was reading the same file


Both functions were async so we could not determine when each function was running and which will be executed first.

So when i tried to run the app i came across with UnauthorizedAccessException because both function maybe were trying to access the file the same time. So i have to make one function wait. You can achieve that by many ways. I used the below function.



But i want to execute this code only once. So i used localSettings



2 Replies to “UnauthorizedAccessException C# File.IO Async”

  1. This is a bad hacky workaround. If you have code accessing a file in multiple spots and especially in multiple threads you should be using a lock around the code accessing the file so that the other file can’t access at the same time.

    1. Yes, that’s the right way to do this, but i had to run 2 async operations on startup and that way worked as well

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.