gpt4 book ai didi

c# - 我可以处理这个流吗?

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:20 26 4
gpt4 key购买 nike

我的 WPF 应用程序中有以下转换器:

[ValueConversion(typeof(byte[]), typeof(ImageSource))]
public class ReturnLabelImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var byteArray = value as byte[];
if (byteArray == null)
return new BitmapImage();
return BuildReturnLabelImageSource(byteArray);
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}

public static ImageSource BuildReturnLabelImageSource(byte[] image)
{
if (image == null)
return null;
var imgBrush = new BitmapImage
{
CacheOption = BitmapCacheOption.OnLoad,
CreateOptions = BitmapCreateOptions.PreservePixelFormat
};
imgBrush.BeginInit();
imgBrush.StreamSource = ConvertImageToMemoryStream(image);
imgBrush.EndInit();
return imgBrush;
}

public static MemoryStream ConvertImageToMemoryStream(byte[] img)
{
var ms = new MemoryStream(img);
return ms;
}
}

我的代码审查员给了我应该处理流的建议。我不太清楚我应该怎么做。我想到的最好的主意是:

    public static ImageSource BuildReturnLabelImageSource(byte[] image)
{
if (image == null)
return null;
var imgBrush = new BitmapImage
{
CacheOption = BitmapCacheOption.OnLoad,
CreateOptions = BitmapCreateOptions.PreservePixelFormat
};
using (var stream = ConvertImageToMemoryStream(image))
{
imgBrush.BeginInit();
imgBrush.StreamSource = stream;
imgBrush.EndInit();
return imgBrush;
}
}

我走在正确的轨道上了吗,还是我应该采取不同的做法?

最佳答案

BitmapImage.StreamSource 的文档说:

Set the CacheOption property to BitmapCacheOption.OnLoad if you wish to close the stream after the BitmapImage is created. The default OnDemand cache option retains access to the stream until the bitmap is needed, and cleanup is handled by the garbage collector.

由于您相应地设置了 CacheOptionimgBrush 应该不再需要在 EndInit 之后访问流(至少,我会这样解释引用的段落),所以你的代码对我来说看起来是正确的。


PS:是的,处置所有 IDisposable 是一种很好的做法,但在您的情况下,它只是一个内存流。与文件流或数据库连接不同,内存流没有任何需要释放的非托管资源。事实上,根据 reference sourceMemoryStream.Dispose 所做的就是确保在您尝试再次读取它时抛出异常,这样我就不会为此失眠。

关于c# - 我可以处理这个流吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23657606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com