Process Bitmap object asynchronously using C #

That I am trying to process a bitmap object in multiple threads. I am creating an object on the UI thread and I want to save it asynchronously. After calling the save method, I continue to process and manipulate the bitmap in several ways.

When the main thread changes the bitmap, the asynchronous thread throws an error or mangles the stream. I tried using async / await and ThreadStart implementations, both results are the same.

I was able to fix this by copying the bitmap stream and sending the new stream to the async method, but this has a performance limitation. Copying it takes almost half the time it takes to save it, especially when working with large streams.

I was wondering if anyone has a workaround for this scenario.

+3


source to share


2 answers


I am guessing this question is about the System.Drawing.Bitmap class. Almost any non-trivial bitmap operation invokes the Bitmap.LockBits () equivalent under the hood. This includes Image.Save (), Graphics.FromImage (), Bitmap.SetPixel (), etc. This lock can only be held one thread at a time. Any other thread that tries to block the bitmap will throw an exception.

This way you are completely confident that neither of the two threads can access the bitmap at the same time. In other words, you must use a keyword lock

in your code to ensure that the stream is blocked when a bitmap is used. Note the inevitable loss of concurrency that you get from this, your UI thread will be stopped while your worker thread is modifying the bitmap if it wants to draw the bitmap at the same time.



Beware that this is not always possible. For example, you cannot change the PictureBox class to insert the required one lock

. Same story for the BackgroundImage property. Etcetera. As a consequence, you can no longer use these conveniences / properties, you will have to paint yourself so you can insert the lock.

+5


source


You can use the Parallel class in the System.Threading.Tasks namespace. The following link contains some examples and explanations.



+2


source







All Articles