Question

I got Collection of Bitmap objects. In need to create mutiple Tasks, pass this Collection as argument. In task method i will read height/width of each Bitmap, then send this Collection and height/width array to Wcf service.

So is it threadsafe operation? How should i act in this case?

Was it helpful?

Solution

It is not, Bitmap doesn't behave much like a "normal" object at all. Many operations on a Bitmap object involve an underlying call to Bitmap.LockBits(). Simple things you'd do, like calling the Save() method or drawing the bitmap with Graphics.DrawImage() or the infamously slow GetPixel() method need to lock the bitmap to get access to a memory-mapped view of the pixel data.

You may recognize the terminology, the same low-level operating system feature is exposed in the .NET Framework by the MemoryMappedFile class. Important for bitmaps, they can contain a huge amount of data. By using an MMF, that pixel data can be kept out of the paging file and page-faulted back into RAM from the image file.

This has many side-effects, it for example explains the common problem that programmers run into when they discover that the image file is locked and cannot be overwritten. The MMF imposes that lock. And a hard constraint is that a bitmap can be locked only once. Or in other words, only one non-trivial operation on the Bitmap object can occur at the same time. Your code is therefore liable to randomly crash when another worker thread tries to do something with the same bitmap object and you don't add the synchronization required to prevent this from happening.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top