开发者

Static method as library

开发者 https://www.devze.com 2023-03-15 08:12 出处:网络
I simply use a static method to convert byte to image. In a multithreaded environment is it safe or should I have to instantiate

I simply use a static method to convert byte to image. In a multithreaded environment is it safe or should I have to instantiate every call?

 namespace Library
 {

 开发者_如何学编程  public static class ByteToImage
   {
      public static Image Convert(byte[] byteArrayIn)
      {
          MemoryStream ms = new MemoryStream(byteArrayIn);
          Image returnImage = Image.FromStream(ms);
          return returnImage;
      }
   }
 }


It is not using anything outside the method so it is thread safe so long as nothing is also updating the byteArrayIn in another thread.

namespace Library
{

   public static class ByteToImage
   {
      public static Image Convert(byte[] byteArrayIn)
      {
          Image returnImage = Image.FromStream(ms);
          return returnImage;
      }
   }
 }

UPDATE

I orignally advices to close the stream. Howeve, as was pointed out in the comments, this particular operation requires the stream to stay open for the lifetime of the Image. See MSDN

However, in general it is always a good idea to clean up streams in a using block to ensure it is done.


It's not using a shared resources so it's ok so long as nothing is also updating the byteArrayIn in another thread as Colin said


Static methods are thread safe if they are not using any shared resources.

Yours does not use any shared resource so it is OK - unless somewhere else in the code you are using the same image.

0

精彩评论

暂无评论...
验证码 换一张
取 消