1 year ago

#331278

test-img

privm

FileSystemWatcher hangs after a few days

I have a Windows service, that watches a folder for newly created files and copies them to another folder. This folder has high traffic and the events are queued.

The service runs fine but after a few days, it hangs for many hours not doing any job. Later it just starts working again and continues the job, and the accumulated events are then processed. Meanwhile, the service is not crashing.

What went wrong?

The service starts like this:

protected override void OnStart(string[] args)
{
    Log.AddLog("starting up");
    FolderWatcher folderWatcher = new FolderWatcher();
    folderWatcher.Start();
}

This is my file system watcher class:

public class FolderWatcher
{
    private FileSystemWatcher watcher;

    public void Start()
    {
        Dispatcher changeDispatcher = null;
        ManualResetEvent changeDispatcherStarted = new ManualResetEvent(false);
        Action changeThreadHandler = () =>
        {
            changeDispatcher = Dispatcher.CurrentDispatcher;
            changeDispatcherStarted.Set();
            Dispatcher.Run();
        };
        new Thread(() => changeThreadHandler()) { IsBackground = true }.Start();
        changeDispatcherStarted.WaitOne();

        watcher = new FileSystemWatcher(sourceFilesPath);
            watcher.Filter = "*.xml";
            watcher.IncludeSubdirectories = true;
            watcher.InternalBufferSize = 65536;
            watcher.EnableRaisingEvents = true;

            watcher.Created += (sender, e) => changeDispatcher.BeginInvoke(new Action(() => OnCreated(sender, e)));
    }

    public static void OnCreated(Object sender, FileSystemEventArgs e)
    {
        //process the files here
    }
}

thanks

c#

.net

events

filesystemwatcher

0 Answers

Your Answer

Accepted video resources