【发布时间】:2016-08-20 12:14:15
【问题描述】:
我构建了一个 windows-forms-app 应用程序,我(尝试)在使用 FileSystemWatcher 观察的特定目录中创建图像时对图像进行大量计算。
private void OnNewFileInDir(object source, FileSystemEventArgs evtArgs)
{
//Load the actual image:
imageFilepath = evtArgs.FullPath; //imageFilepath is a private class string var
Image currentImage = Image.FromFile(imageFilepath);
//Display the image in the picture box:
UpdatePictureBox(currentImage); //Method to update the GUI with invoking for the UI thread
//Extensive Calculation on the images
Image currentResultImage = DoExtensiveWork(currentImage);
// Put the current result in the picture box
UpdatePictureBox(currentResultImage );
//dispose the current/temporary image
currentImage.Dispose();
}
将新文件粘贴到目录时正确触发该事件。但我得到一个“System.OutOfMemoryException”就行了
Image currentImage = Image.FromFile(imageFilepath);
当我将这段代码(使用相同的文件路径)完全放在按钮事件中(因此不使用 FileSystemWatcher)时,一切正常。所以我认为线程存在一些问题,因为扩展计算随后由 FileSystemWatcher-Thread 调用,而不是由 UI 线程调用。
我尝试过这样的事情:
//TRY 1: By executing a button click method containg the code
pb_Calculate_Click(this, new EventArgs()); //This does not work eigther --> seems to be a problem with "Who is calling the method"
//TRY 2: Open a new dedicated thread for doing the work of the HistoCAD calculations
Thread newThread_OnNewFile = new Thread(autoCalcAndDisplay);
newThread_OnNewFile.Start();
//TRY 3: Use a background worker as a more safe threading method(?)
using (BackgroundWorker bw = new BackgroundWorker())
{
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
if (bw.IsBusy == false)
{
bw.RunWorkerAsync();
}
}
不幸的是,它们都不可靠。第一个根本没有。第 2 项仅偶尔有效,第 3 项也有效。
你们中的一些人知道那里发生了什么吗?我该怎么做才能使其正常工作?谢谢!
编辑: 感谢cmets: 我还尝试在每个事件上调用 GC.collect() 并尝试尽可能包含 using() 和 dispose() 。当我手动(使用按钮)执行该过程时,即使在一个接一个地处理大量文件时它也可以工作。但是,当使用事件处理程序完成时,即使在我复制到文件夹中的第一个文件上,我有时也会得到 outOfMem-Exception。文件始终是相同的 BMP,大小为 32MB。这是处理一张图像的内存使用量:
编辑 2: 我创建了一个最小的示例(带有一个图片框和一个按钮样式的复选框的 GUI)。事实证明,同样的事情正在发生。 OutOfMemException 发生在同一行(图像...)。特别是对于大型 BMP,几乎总是会发生异常:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MinimalExampleTesting
{
public partial class Form1 : Form
{
private string imageFilepath;
private string autoModePath = @"C:\Users\Tim\Desktop\bmpordner";
//Define a filesystem watcher object
private FileSystemWatcher watcher;
public Form1()
{
InitializeComponent();
/*** Creating as FileSystemEventArgs watcher in order to monitor a specific folder ***/
watcher = new FileSystemWatcher();
Console.WriteLine(watcher.Path);
// set the path if already exists, otherwise we have to wait for it to be set
if (autoModePath != null)
watcher.Path = autoModePath;
// Watch for changes in LastAccess and LastWrite times and renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch for BMP files.
watcher.Filter = "*.bmp";
// Add event handler. Only on created, not for renamed, changed or something
// Get into the list of the watcher. Watcher fires event and "OnNewFileCreatedInDir" will be called
watcher.Created += new FileSystemEventHandler(OnNewFileInDir);
}
private void tb_AutoMode_CheckedChanged(object sender, EventArgs e)
{
//First of all test if the auto mode path is set and correctly exists currently:
if (!Directory.Exists(autoModePath) || autoModePath == null)
{
MessageBox.Show("Check if Auto Mode path is correctly set and if path exists",
"Error: Auto Mode Path not found");
return;
}
// Begin watching if the AutoModePath was at least set
if (autoModePath != null)
{
watcher.EnableRaisingEvents = tb_AutoMode.Checked; //Since we have a toogle butten, we can use the 'checked' state to enable or disable the automode
}
}
private void OnNewFileInDir(object source, FileSystemEventArgs evtArgs)
{
Console.WriteLine("New file in detected: " + evtArgs.FullPath);
//Force a garbage collection on every new event to free memory and also compact mem by removing fragmentation.
GC.Collect();
//Set the current filepath in the class with path of the file added to the folder:
imageFilepath = evtArgs.FullPath;
//Load the actual image:
Image currentImage = Image.FromFile(imageFilepath);
UpdatePictureBox(currentImage);
}
private void UpdatePictureBox(Image img)
{
if (pictureBox_Main.InvokeRequired)
{
MethodInvoker mi = delegate
{
pictureBox_Main.Image = img;
pictureBox_Main.Refresh();
};
pictureBox_Main.Invoke(mi);
}
else { //Otherwise (when the calculation is perfomed by the GUI-thread itself) no invoke necessary
pictureBox_Main.Image = img;
pictureBox_Main.Refresh();
}
img.Dispose();
}
}
}
提前感谢您的进一步提示:)
【问题讨论】:
-
Image currentImage = Image.FromFile(imageFilepath);与 UI 线程无关。如果是这样,您将获得System.InvalidOperationException。我认为您的问题与您的图像在您阅读之前没有完全写入有关。 -
你能说明你是如何创建 FileSystemWatcher 的吗?
-
Image 类是一个单一的 .NET 类,对于忘记调用 Dispose() 来说是非常无情的。它使用非常少的 GC 堆和 很多 非托管内存。非常糟糕,因为您的代码似乎没有给 GC 提供太多锻炼,因此您没有为您清理它。水晶球说您的 UpdatePictureBox() 忘记处理旧的 PictureBox.Image。如果这没有帮助,那么使用内存分析器或绝望地计算 OnNewFileInDir() 调用并调用 GC.Collect() ,例如 100 次。
-
从代码中看不出一个 32MB 的 bmp 图像如何可能导致您的程序需要几乎一个千兆字节。您现在可能会遇到 32 位进程的限制,当程序运行一段时间并且地址空间变得碎片化时,需要约 90 MB 的单个分配可能会失败。消除强制抖动使其可以作为 64 位进程运行是非常简单的解决方法。
-
@Hans:在后台(当使用 1GB 时)有一个非常复杂的 DLL,它将图像分割成图块并计算每个图块的 200 多个属性。
标签: c# multithreading image out-of-memory filesystemwatcher