'Occasionally getting a generic error occurred in GDI+ in a C# program that takes a screenshot every 15 seconds

I have a C# program that takes a screenshot every 15 seconds that works great. But now I seem to get an occasional "a generic error occurred in GDI+". I am then using a javascript file that looks at the refreshed jpeg every 13 seconds. I assume that the problem is the javascript file is reading the picture the same time as the C# program is updating the file. I am not worried if the picture doesn't get updated every time (this is just an information screen that can be delayed 30 seconds without causing any problems). I am looking for a way to program that if it can't save the file for any reason, just try again next time, but not show an error. Below is the logic. Thanks.

    private void takeScreenShot()
    {
        Rectangle bounds = Screen.PrimaryScreen.Bounds;
        using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
            bitmap.Save(c:\\screen.jpg", ImageFormat.Jpeg);
        }
    }


Solution 1:[1]

Ignoring exceptions using a try/catch is one solution. I'm sure it will be okay for a simple little program like this, but I can never support blanket exception ignoring.

When you have two different programs that run completely independently and rely upon a stream of data between them the answer to many problems like this is pooling/queuing. Rather than maintaining one single image file that you're constantly overwriting and trying to read you should have a rolling file sequence.

On the C# side you have it create a new file every time it takes a screenshot. Once you have 2-3 images in the directory you have it delete the oldest one every time it makes the new one.

On the JavaScript side you have it pull the latest image at the time that it's run. Worst case scenario here is that you end up opening up one image a millisecond before the latest one gets created. That would result in the largest possible gap of a missed image given your timer offsets between the two programs.

It's a few extra lines of code on each end, and you have eliminated the possibility that you're trying to overwrite a file that's opened already.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Logarr