techno
techno

Reputation: 6526

Files processed more than once while using File System Watcher

Im using file system watcher to watch a directory and process files as new ones are created.Im using a timer with background worker to prevent concurrency issues and memory overflow.

This is what i have

 //creating the watcher 

            watcher = new FileSystemWatcher();
            watcher.Path = @"C:\Users\me\Desktop\watch";
             watcher.Filter = "*.*";
            watcher.Created += new FileSystemEventHandler(copied);
            watcher.EnableRaisingEvents = true;



//hooking to creation event

 void copied(object sender, FileSystemEventArgs e)
        {
            if (bwork.IsBusy == false)
            {
                bworkprocesslist.Add(e.FullPath);

            }
            else
            {
                bworkpendinglist.Add(e.FullPath);

            }


          }

  //used timer to prevent concurrent access of resources and memory overflow

 private void timer1_Tick(object sender, EventArgs e)
        {
            if (bwork.IsBusy==false)
            {
                bwork.RunWorkerAsync();
            }

        }


// Maintaining Lists and removed processed file from the main list 

 private void bwork_DoWork(object sender, DoWorkEventArgs e)
        {
            List<string> removedfiles = new List<string>();
            foreach (string pfile in bworkprocesslist)
            {
            process(pfile) //Do processing of pfile
            removedfiles.Add(pfile);
            }
       foreach (string x in removedfiles)
        {

            bworkprocesslist.Remove(x);
        }


        }

//Add files from pending list after background worker completion



 void bwork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            foreach (string s in bworkpendinglist)
            {
                bworkprocesslist.Add(s);
                bworkpendinglist.Remove(s);
            }
        }

The code works without any issues.But it sometimes processes a file more than once.I cannot figure where the error occurs.

Upvotes: 0

Views: 99

Answers (2)

Richy Rich
Richy Rich

Reputation: 33

It seems like inside bwork_RunWorkerCompleted you are taking entries from your bworkpendinglist and adding them to your bworkprocesslist, but there's nowhere in the code I can see that you're removing from the bworkpendinglist.

i.e. Once you've added them to your bworkprocesslist you should remove them from the bworkpendinglist.

Upvotes: 0

Andrey Korneyev
Andrey Korneyev

Reputation: 26896

It doesn't looks like there is some error here.

From MSDN article:

Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events.

Upvotes: 1

Related Questions