【问题标题】:Out-of-mem-Exception in c# GUI when using FileSystemWatcher - multithreading使用 FileSystemWatcher 时 c# GUI 中的 Out-of-mem-Exception - 多线程
【发布时间】: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


【解决方案1】:

已解决:

问题似乎是,该事件被立即触发,但文件尚未最终复制。这意味着我们必须等到文件空闲。 事件开始时的 Thread.Sleep(100) 完成这项工作。因为我现在知道要搜索什么,所以我找到了两个链接: Thisthis 在哪里可以找到:

创建文件后立即引发 OnCreated 事件。如果正在将文件复制或传输到监视目录中,则会立即引发 OnCreated 事件,然后引发一个或多个 OnChanged 事件

因此,最适合我的情况是包含一种方法来测试文件是否仍处于锁定状态,而不是在事件开始时等待文件解锁。不需要额外的线程或 BackgroundWorker。 见代码:

private void OnNewFileInDir(object source, FileSystemEventArgs evtArgs)
{
   Console.WriteLine("New file detected: " + evtArgs.FullPath);

   //Wait for the file to be free
   FileInfo fInfo = new FileInfo(evtArgs.FullPath);
   while (IsFileLocked(fInfo))
   {
       Console.WriteLine("File not ready to use yet (copy process ongoing)");
       Thread.Sleep(5);  //Wait for 5ms
   }

   //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 static bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;
    try
    {
        //try to get a file lock
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
       //File isn't ready yet, so return true as it is still looked --> we need to keep on waiting
       return true;
    }
    finally
    {
        if (stream != null){ 
            stream.Close();
            stream.Dispose();
        }
    }
    // At the end, when stream is closed and disposed and no exception occured, return false --> File is not locked anymore
    return false;
}

尽管如此:感谢您的帮助...它让我走上了正轨;)

【讨论】:

  • 恭喜。很高兴看到你自己找到了它!
【解决方案2】:

正如 MSDN 所说的 FileSystemWatcher

常见的文件系统操作可能引发多个事件。例如,当一个文件从一个目录移动到另一个目录时,可能会引发几个 OnChanged 以及一些 OnCreated 和 OnDeleted 事件。移动文件是一个复杂的操作,由多个简单的操作组成,因此会引发多个事件。同样,某些应用程序(例如防病毒软件)可能会导致 FileSystemWatcher 检测到的其他文件系统事件。

也许你的图片被加载了好几次。

为了测试它,你可以在imageFilepath = evtArgs.FullPath;之后添加这一行

imageFilepath = evtArgs.FullPath;
Task.Run(()=>{MessageBox.Show(imageFilepath);});

这将通知您Created 事件已被触发,并且不会阻止您的程序。

编辑

将提供OutOfMemory 的代码行放入Try Catch 中。 就像thisthis 问题描述的那样,如果您的图像损坏,您可能会收到此错误。

【讨论】:

  • 我添加了这一行,它只是在消息框中显示了正确的新文件路径。 OutOfMemException 在那之后仍然发生
  • 你只得到一次消息框?
  • 是的,只有一个 msgbox!我以前读过第一篇文章,也试过了。但我认为这不太可能是因为图像格式。因为它在没有 FileSystemWatcher 的情况下工作,例如在一个额外的按钮中。不过还是谢谢!
  • 顺便说一句:我可以用任何其他程序(windows pic view、paint、PS)打开图像,并且它有时也可以与该程序一起使用。在我的 PC 上,我有 8GB 的​​ RAM,并且目前在 Win10 中至少有 4GB 可用。并且:我也尝试了不同的(和小型的)BMP。 BMP 越小,我必须将新 BMP 粘贴到文件夹中以获取错误的速度越快(对于 500 kB BMP,大约每秒 2-3 个)
  • 我会为您提供更多帮助,但恐怕我无法为您提供更多帮助。
猜你喜欢
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
相关资源
最近更新 更多