【发布时间】:2016-09-12 11:03:44
【问题描述】:
我想要一个应用程序来监控某个文件夹并显示该文件夹中出现的新图像。我成功地使用FileSystemWatcher 类检测到新图像,但是我在显示它们时遇到了问题。我有以下代码:
public partial class MainWindow : Window
{
FileSystemWatcher watcher = new FileSystemWatcher();
public MainWindow()
{
InitializeComponent();
watcher.Path = "C:/Users/maciejt/Pictures";
watcher.Filter = "*.jpg";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.EnableRaisingEvents = true;
}
private void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
image.Dispatcher.Invoke(new Action(() => { image.Source = new BitmapImage(new Uri(e.FullPath)); }));
}
}
它适用于大约 10-20 个小 (~100kB) 图像和 1-2 个大 (~4MB) 图像。稍后它会抛出图像被另一个进程使用的异常。我还在调试器中观察到,应用程序使用的内存随着每个新图像而急剧增加,就像以前的图像没有被释放一样。
创建BitmapImage 并将其显示在Image 控件中的正确方法是什么?
编辑:
我已经尝试了一个可能重复的解决方案,但是这仍然给了我同样的异常,这次甚至没有工作一次。下面是修改后的代码:
private void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
image.Dispatcher.Invoke(new Action(() => { image.Source = LoadBitmapImage(e.FullPath); }));
}
public static BitmapImage LoadBitmapImage(string fileName)
{
using (var stream = new FileStream(fileName, FileMode.Open))
{
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage;
}
}
【问题讨论】:
标签: c# multithreading user-interface