How to handle large volume of filewatcher events without any delay in processing
<p>To handle large volume of file watcher events, I have implemented the below code in my file watcher.</p>

<p>I have copied a folder to a watched location The folder has around 40K files and folders in it. The issue is the queue items are not getting processed immediately. The processing happening in a period of time. ie The folder copying  took around 40 minutes. But the processing queue took around 4-5 hours from the beginning of the file copying</p>

<p>I am expecting the events to be processed immediately after copying the folder.</p>

<p>Here is my FileProcessor class:</p>

<pre><code>class FileProcessor
{
    private Queue&lt;string&gt; workQueue;
    private Thread workerThread;
    private EventWaitHandle waitHandle;

    public FileProcessor()
    {
        workQueue = new Queue&lt;string&gt;();
        waitHandle = new AutoResetEvent(true);
    }

    public void QueueInput(string filepath)
    {
        workQueue.Enqueue(filepath);

        // Initialize and start thread when first file is added
        if (workerThread == null)
        {
            workerThread = new Thread(new ThreadStart(Work));
            workerThread.Start();
        }

        // If thread is waiting then start it
        else if (workerThread.ThreadState == ThreadState.WaitSleepJoin)
        {
            waitHandle.Set();
        }
    }

    private void Work()
    {
        while (true)
        {
            string filepath = RetrieveFile();

            if (filepath != null)
                ProcessFile(filepath);
            else
                waitHandle.WaitOne();
        }
    }

    private string RetrieveFile()
    {
        if (workQueue.Count &gt; 0)
            return workQueue.Dequeue();
        else
            return null;
    }

    private void ProcessFile(string filepath)
    {
        // Some processing done on the file

    }
}
</code></pre>

<p>It is used whenever the FileSystemWatcher.Created event is raised:</p>

<pre><code>FileProcessor fileprocessor = new FileProcessor()

void onCreated(object source, FileSystemEventArgs e)
{
    try
    {
        fileprocessor.QueueInput(e.FullPath);
    }
    catch (Exception ex)
    {

    }
}
</code></pre>
