0

I am trying to store a file in local directory using Windows.Storage but I get an error when I try to store a second image

I am using the Windows.Storage

async void ReceiveDecodedData(byte[] data, int width, int height)
{
   StorageFolder storageFolder = KnownFolders.PicturesLibrary;

   string filename = "sample" + ".jpg";

   StorageFile file = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
   await FileIO.WriteBytesAsync(file, data);

}

I want to write the bytes to the image without any error/exceptions.

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

  • 1
    `async void` is likely your problem, this should be `async Task` and you should await the call to this method. Making it `async void` means you cannot wait for this method to finish and subsequent calls to will try to open and write `smaple.jpg` while it is still being written to. – JSteward Oct 21 '19 at 21:03
  • @JSteward I am using the ReceiveDecodedData() elsewhere and it has to be a void videoParser.SetSurfaceAndVideoCallback(0, 0, swapChainPanel, ReceiveDecodedData); – Hemachandra Ghanta Oct 21 '19 at 21:10
  • Are you intending to keep overwriting the same file? Because that's what this code tries to do – ADyson Oct 21 '19 at 22:34
  • @ADyson my final result is to get those images but I won’t me saving them locally – Hemachandra Ghanta Oct 21 '19 at 22:36
  • 1
    I'm not sure if that actually answers my question. "Yes" or "no" would have been sufficient. Your sentence doesn't actually make any grammatical sense, I don't know what you're trying to say, or how it relates to my simple question – ADyson Oct 21 '19 at 22:40

1 Answers1

0

If the method does not return a Task then you can't use it within an async/await pattern. JSteward is correct that you should replace async void with async Task. If you are calling the function somewhere else then create a synchronous version of the method and call the same underlying function.

How and when to use ‘async’ and ‘await’

Zakk Diaz
  • 1,063
  • 10
  • 15