Polamin Singhasuwich
Polamin Singhasuwich

Reputation: 1766

C# How to use MemoryStream with multithreading

My current code is:

public static byte[] ImageToByte(Image img)
{

        byte[] byteArray = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            stream.Close();
            byteArray = stream.ToArray();
        }


        return byteArray;
}

Is there any way to make this work with multithreading, or use every core of my CPU to make it faster?

Upvotes: 4

Views: 6162

Answers (3)

Jacob
Jacob

Reputation: 759

It's not possible to do it multithreaded. Doing so might damage the stream. The image must be saved to the stream at an offset of zero. If any additional data has been written to the stream before saving the image, the image data in the stream will be corrupted.

MSDN

Upvotes: 2

edepperson
edepperson

Reputation: 1035

I wouldn't know how to make it use multiple cores, but to make it threadsafe you need to do the following. First declare a private static Object

private static readonly Object _obj = new Object();

Then modify your code as below:

public static byte[] ImageToByte(Image img)
{
    lock(_obj)
    {
        byte[] byteArray = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            stream.Close();
            byteArray = stream.ToArray();
        }

        return byteArray;
    }
}

Upvotes: -1

appcoder
appcoder

Reputation: 649

If you are converting multiple images to byte array and you know them upfront, then you can use the Parallel.ForEach loop and have this done there so that they can be done in different cores if available. But i do no think modifying this single method to use multiple cores is worth the effort and saves any time.

Upvotes: 5

Related Questions