C#C
C#3y ago
Denis

✅ FileSystemWatcher - avoiding buffer overflow

I have a file-based communication protocol - insane, I know.
It is used to communicate many messages a second.

The FileSystemWatcher has a default buffer size of 8KB, which allows up to 15 notifications, assuming the filenames are 260 characters long.
Let's say I increase the buffer size 2x.
Is there anything else I can do to avoid the notification buffer from overflowing?

I have also configured the following:
      _watcher = new FileSystemWatcher
      {
        Path = _path,
        InternalBufferSize = 16_384, // 16KB
        IncludeSubdirectories = false,
        Filter = "*_*_*_*_*" + Constants.FILE_EXTENSION,
        NotifyFilter = NotifyFilters.CreationTime
      };
      _watcher.Created += OnCreated;


I'm also thinking about invoking the body of the OnCreated handler in a background thread. Is that a bad idea?

private void OnCreated(object source, FileSystemEventArgs e)
{
  ThreadPool.QueueUserWorkItem(_ =>
  {
    var fullName = Path.GetFileNameWithoutExtension(e.FullPath);
    var isMatch = Regex.IsMatch(fullName, pattern);

    if (!isMatch)
      return;

    if (DisableFileQueue)
      NewMessage?.Invoke(this, e.FullPath);
    else
      FileQueue.Add(e.FullPath);
  });
}
Was this page helpful?