C # How to use a MemoryStream with multi-threaded

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 a way to make this work multithreaded or use each core of my processor to make it faster?

+4
source share
3 answers

If you convert several images into an array of bytes, and you know them in advance, you can use the Parallel.ForEach loop and do this so that they can run in different cores, if available. But I don’t think that changing this single method to use multiple cores is worth the effort and saves any time.

+5
source

. . . - , .

MSDN

+1

I do not know how to make it use multiple cores, but to make it thread safe, you need to do the following. First declare a closed static object

private static readonly Object _obj = new Object();

Then change 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;
    }
}
-one
source

Source: https://habr.com/ru/post/1502630/


All Articles