Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading;
Using System.Threading.Tasks;
Using System.IO;
Using System.Collections;
Namespace Demo
{
public class Filelisten
{
Private AutoResetEvent AutoResetEvent;
private string Listenpath = @ "d:\ project information \ essay \demo\listen";
Private queue Filequeue = new Queue ();
private static Object Objlock = new Object ();
private bool iswait = true;
Public Filelisten (String listenpath)
{
This.listenpath = Listenpath;
Init ();
}
private void Init ()
{
FileSystemWatcher watcher = new FileSystemWatcher (Listenpath);
Watcher. NotifyFilter = Notifyfilters.lastaccess | Notifyfilters.lastwrite | Notifyfilters.filename | Notifyfilters.directoryname;
Watcher. Filter = "*.txt";
Watcher. EnableRaisingEvents = true;
Watcher. Created + = new FileSystemEventHandler (monitorfilecreate);
AutoResetEvent = new AutoResetEvent (false);
Thread thread = new Thread (DoWork);
Thread. Start ();
Reload ();
}
private void Reload ()
{
DirectoryInfo dires = new DirectoryInfo (Listenpath);
fileinfo[] files = dires. GetFiles (). (c = c.creationtime). ToArray ();
foreach (FileInfo file in files)
{
if (!filequeue.contains (file. FullName))
{
Filequeue.enqueue (file. FullName);
Sleep 1 seconds
Thread.Sleep (1000);
AutoResetEvent.Set ();
}
}
}
private void DoWork ()
{
Console.WriteLine ("DoWork Begin");
Wait for the signal
while (iswait)
{
Autoresetevent.waitone ();
locking prevents concurrency
Lock (Objlock)
{
Get file queue information and remove
String path = Filequeue.dequeue (). ToString ();
Console.WriteLine ("Processing = =" + path);
Console.WriteLine ("In Process ...");
Console.WriteLine ("Processing Done");
File.delete (path);
}
}
}
private void Monitorfilecreate (object sender, FileSystemEventArgs e)
{
if (e.ChangeType = = watcherchangetypes.created)
{
Try
{
if (!filequeue.contains (E.fullpath))
{
Console.WriteLine ("Listening File = =" + E.fullpath);
Filequeue.enqueue (E.fullpath);
AutoResetEvent.Set ();
}
}
catch (Exception ex)
{
Loghelper.error (ex. Message + "\ r \ n" + ex. StackTrace);
}
}
}
}
}
C # FileSystemWatcher concurrency