-1

I wrote something in C# like

while(1){
  Bitmap b = BitMapFromSomewhereElse();
  b.save("a.jpg");
}

in order to let the image update real-time. But I always get System.Runtime.InteropServices.ExternalException: Generic error in GDI+

What's the problem here? Maybe I'm writing too fast, if I do this loop 500ms a time, the error will come out after several seconds, and if I do this 5000 ms a time, the error does not appear. I searched and tried a lot of methods, like calling Dispose() or using(b=...)... but none of those worked.

Panda Lee
  • 19
  • 3
  • This is generally a horrible way to handle something. Where is BitMapFromSomewhereElse() coming from? If it is a file.. See this post: https://stackoverflow.com/questions/721714/notification-when-a-file-changes Otherwise.. you could put a timer in there.. sleeping is generally a bad practice but not nearly as bad as WHILE(TRUE) – Señor CMasMas Jan 11 '19 at 18:16
  • 2
    If you are constantly saving the file, probably you won't be able to use or read the file anywhere else. Also this is a good way to have your program flagged as potentially dangerous by an antivirus software. – Josh Part Jan 11 '19 at 18:20
  • Use a `FileSystemWatcher` like in @SeñorCMasMas's linked post. Using an infinite loop not only locks up the thread, but having it check every X seconds is not "real time". It's going to be *incredibly* wasteful to be saving a file to disk that often. (and **definitely** use `using` blocks) – Broots Waymb Jan 11 '19 at 18:21
  • This code consumes 100% CPU time continuously. It would last about 2 seconds on my machine before I deleted it and hurried to give an extremely negative review on every site I could find related to the program. – Ken White Jan 11 '19 at 18:58

1 Answers1

2

Perhaps the problem is you're not releasing resources. Bitmap is a disposable object, so you should be disposing it:

while(1){
    using (Bitmap b = BitMapFromSomewhereElse()) {
        b.save("a.jpg");
    }
}

It really depends on whether BitMapFromSomewhereElse is creating a new bitmap every time you call it, or if it's just returning a reference to an existing bitmap. If the former, then you need to call Dispose. If the latter, then Dispose shouldn't be necessary, so long as whatever creates the bitmap originally ends up disposing it at some point.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351