Skip to main content
 首页 » 编程设计

c#之为什么我的图像被另一个进程锁定

2024年02月01日32hnrainll

我构建了一个在 WPF 中运行的数字标牌解决方案。我有一个处理调度的可执行文件和一些负责显示图像、视频等的外部程序集(带有用户控件的 .dll)。

当应用程序启动时,它会将所有程序集加载到一个列表中,然后使用一个 XML 文件,其中包含关于哪种幻灯片以哪些参数开始的配置信息,如下所示:

<signage> 
  <slide type="image" argument="c:\image1.png"/> 
  <slide type="image" argument="c:\image2.png"/> 
  <slide type="video" argument="c:\video1.mpg"/> 
  ... 
</signage> 

该列表可能很长并且包含许多不同的幻灯片。当我构建要显示的对象列表时,我通过反射创建了一个我需要显示的 .dll 的新实例,并将参数传递给它。这包含在一个列表中。然后父可执行文件遍历列表并在我的主 WPF 应用程序上显示用户控件实例(实例化的幻灯片类型)。

这就是我的问题的背景。

当我需要在运行时更新内容时,我需要替换磁盘上的文件(image1、image2 等...),但出现异常,文件正在被另一个进程使用,我无法访问它们。

知道如何解决这个问题吗?有什么办法可以从我的应用程序中“卸载”它们吗?有没有办法以正确的方式做到这一点?

编辑 以下是有关我如何在图像集合中执行此操作的一些附加信息:

public ImageExtensionControl(XmlDocument document, Dictionary<string, string> settings, Action slideFinished) 
        { 
            InitializeComponent(); 
            string path = new FileInfo(Assembly.GetCallingAssembly().Location).Directory.FullName; 
            string id = settings["Image"]; 
            path = System.IO.Path.Combine(path, document.SelectSingleNode("properties/files/file[@id='" + id + "']").Attributes["path"].Value); 
            BitmapImage bitmapImage = new BitmapImage(); 
            bitmapImage.BeginInit(); 
            bitmapImage.UriSource = new Uri(path, UriKind.Absolute); 
            bitmapImage.EndInit(); 
            this.myimage.Source = bitmapImage; 
        } 

请您参考如下方法:

如果您正在加载图像,请确保在完成操作后关闭流。例如,

using(var fs = new FileStream(...)) 
{ 
   // ... 
}  // <-- Stream is closed and disposed.