Using Async to save a FileStream

Viewed 4121

I am trying to save a file(BitmapImage) to a certain location, but as soon as I use async & await I get an error saying the file is in use:

The process cannot access the file 'C:\Users\ ... \image1.jpg' because it is being used by another process.

My coding:

BitmapImage image = new BitmapImage(new Uri(oldImagePath));
var encoder = new JpegBitmapEncoder() { QualityLevel = 17 };
encoder.Frames.Add(BitmapFrame.Create(image));

using (var filestream = new FileStream(GetImageLocation(), FileMode.Create))
    await Task.Run(() => encoder.Save(filestream)); //Error here

When I use the code without the await, the code works perfectly fine. I think it might be because another thread might be using it, but can anyone help or explain to me a work around for my issue? Thank you.

3 Answers
Related