Skip to main content
 首页 » 编程设计

c#之使用静态字典时,我在 ASP.NET 中收到错误 "Item has already been added."

2024年02月23日16bhlsheji

当我使用 f10 调试代码时,它可以正常工作,没有错误!但是在运行时我得到了这个错误: “已添加具有相同键的项目”

请帮忙

我的字典:

public static Dictionary<string, string> ImageFilePath 
        = new Dictionary<string, string>(); 

在同一个 Glob.cs 中使用我的函数:

public static Image ShowImageOnColumn(string Value,byte ImageHeigth,byte ImageWidth) 
{ 
 
   . 
   . 
   . 
 
    string FilePath = "",ImgId = ""; 
 
 
    Image img_ = new Image(); 
 
    Random rnd = new Random(); 
 
    ImgId = rnd.Next(100000000).ToString(); 
    img_.ImageUrl = "ShowImageInRuntime.aspx?FileName=" + ImgId; 
 
    ImageFilePath.Add(ImgId, FilePath); 
 
 
    img_.Height = Unit.Pixel(ImageHeigth); 
    img_.Width = Unit.Pixel(ImageWidth); 
 
    return img_; 
 
   } 

请您参考如下方法:

您没有保护您的 ImageFilePath.Add 调用。如果 key 已经存在,您将得到一个异常提示。

您可以检查 key :

if (ImageFilePath.ContainsKey(ImgId)) 
{ 
    ImageFilePath[ImgId] = FilePath; 
} 

或者你可以在索引上设置,如果它丢失则添加,如果存在则更新:

ImageFilePath[ImgId] = FilePath; 

与调用 Add 相反。

但是请注意,当 IIS 回收工作进程时,静态成员容易丢失。因此,它们往往会被避免。还存在多线程问题,因为静态成员在整个进程中都是可见的。

如果您需要一个随机文件名,请尝试 DateTime.ToString("ddMMyyyyhhmmssfff") 或 Guid.NewGuid(),而不是保留 随机活着。

Path 还具有 GetTempFileName 方法。