【发布时间】:2016-01-28 17:40:30
【问题描述】:
我有一个 asp.net/C# 类,可以调整图像大小以在服务器上作为文件缓存,但是确定使用哪个编码器的代码部分似乎偶尔会抛出 NullReferenceException。
这里是初始化和传回编码器的代码:
public static class ImageUtilities{
private static Dictionary<string, ImageCodecInfo> encoders = null;
public static Dictionary<string, ImageCodecInfo> Encoders{
get{
if (encoders == null){
encoders = new Dictionary<string, ImageCodecInfo>();
}
//if there are no codecs, try loading them
if (encoders.Count == 0){
foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders()){
encoders.Add(codec.MimeType.ToLower(), codec);
}
}
return encoders;
}
}
...
这是引发异常的特定行:
encoders.Add(codec.MimeType.ToLower(), codec);
这是错误文本:
Object reference not set to an instance of an object.
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
这是调用 Encoders 属性的唯一位置(随后是堆栈跟踪中该属性下方的行):
if (Encoders.ContainsKey(lookupKey)){
foundCodec = Encoders[lookupKey];
}
即使lookupKey 为null,查找不应该只返回null 而不是抛出异常吗?
【问题讨论】:
-
这段代码很有可能是从多个线程调用的(因为帖子包含 ASP.NET 标记),因此由于缺乏适当的同步而应该以这种方式失败。