c# - 如何实现延迟位图加载?

标签 c# .net wpf xaml lazy-evaluation

我想编写一个函数,它将作为输入字符串 fileName 并返回 ImageDrawing 对象。
我不想在此函数中从磁盘加载位图。相反,我想要进行某种惰性评估。 为了找出尺寸,我使用了 Bitmap 类。

目前我有这个代码:

    public static ImageDrawing LoadImage(string fileName)
    {
        System.Drawing.Bitmap b = new System.Drawing.Bitmap(fileName);
        System.Drawing.Size s = b.Size ;
        System.Windows.Media.ImageDrawing im = new System.Windows.Media.ImageDrawing();
        im.Rect = new System.Windows.Rect(0, 0, s.Width, s.Height);
        im.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(fileName, UriKind.Absolute));
        return im;            
    }
  1. System.Drawing.Bitmap 构造函数的调用是否是惰性调用?
  2. .Size 的调用是否是懒惰的?
  3. BitmapImage 构造函数是否惰性?
  4. 有没有其他方法可以让我实现完全懒惰?

编辑: 有许多可能对社区有帮助的好答案 - 使用 Lazy 类并通过 Task 打开它。
尽管如此,我想把这个 ImageDrawing 放在 DrawingGroup 中,然后序列化,所以 Lazy 以及 Task 是对我来说不是一个选择。

最佳答案

Bitmap的构造函数类并不懒惰,但您可以使用 Lazy<T>正是为了这个目的而创建的类:

public static Lazy<ImageDrawing> LoadImage(string fileName)
{
    return new Lazy<ImageDrawing>(() => {
        System.Drawing.Bitmap b = new System.Drawing.Bitmap(fileName);
        System.Drawing.Size s = b.Size;
        System.Windows.Media.ImageDrawing im = new System.Windows.Media.ImageDrawing();
        im.Rect = new System.Windows.Rect(0, 0, s.Width, s.Height);
        im.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(fileName,     UriKind.Absolute));
        return im;
    });
}

来自文档 (http://msdn.microsoft.com/en-us/library/dd997286.aspx):

Although you can write your own code to perform lazy initialization, we recommend that you use Lazy instead. Lazy and its related types also support thread-safety and provide a consistent exception propagation policy.

关于c# - 如何实现延迟位图加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806220/

相关文章:

c# - 将字符串转换为日期时间 UTC

c# - 有什么办法可以关闭邮件 smtp session 吗?

wpf - 如何在 GridViewColumn 中居中 WPF CheckBox?

c# Mvvm 用来自 GET 请求的数据填充 ObservableObject 属性

.net - 适用于 .NET 3.5(或 4.0)的优秀 XMPP/Jabber 客户端库

WPF 绑定(bind)渲染 Gui 进度

c# - 在c#中画线

c# - 将项目添加到默认的 TextBox 上下文菜单

c# - 为什么添加 DoubleStructs 比添加 double 慢得多?

c# - .NET (C#) 事件 - 自定义 EventArgs 问题