0

I have a WPF application where I need to save an image to the file system, but I was told to be careful for file share violations. The image keeps getting replaced in a C# DispatcherTimer. I was told to use Thread.Sleep in order to desynchronize the loop. I have several DispatcherTimers running to create images. Is this a proper solution?

    private void SaveImage(Image image, string fileToSave, ImageFormat imageFormat, TimeSpan interval)
    {
        try
        {
            image.Save(fileToSave, imageFormat);
        }
        catch (Exception ex)
        {
            Trace.TraceError("View Capture Service exception on first attempt to save image: " + ex.Message);
            Thread.Sleep(Convert.ToInt32(interval.TotalMilliseconds / 2));
            image.Save(fileToSave, imageFormat);
        }
    }
Ray
  • 4,679
  • 10
  • 46
  • 92
  • 4
    I would not put the `image.Save` in the `catch`... What happens if it throws again? You are basically hoping that it never throws twice, but if it does, you have a potential crash. – Ron Beyer Jun 21 '19 at 18:44
  • Is this the user saving the file? Because a dispatcher time seems inappropriate in that case. It'd be more usual to tell the user they can't save because someone else is using that file. – Andy Jun 21 '19 at 18:51
  • This may be way off base, but how is this method called? By some sort of user action like a command or a button click? If so, could there be a double click causing the issue. – Paul Jun 21 '19 at 19:04
  • This is not the right way to save an image in a WPF application, since it's using WinForms APIs. See the answer to the original question for how to use a BitmapEncoder with a FileStream. In order to avoid that WPF keeps an image file open when you create a BitmapImage, also use a FileStream and assign it to the BitmapImage's Source property. Also *never* call Thread.Sleep in the UI thread. It will block the thread and hence the User Interface. – Clemens Jun 22 '19 at 07:34

0 Answers0