I'm working on a project where i have to observe a directory. The files will be deployed in the directory at the same time. This means there could be 7000 files that will be moved to the directory at once. I'm using the FileSystemWatcher to trigger a thread if a new file ist added to the directory. If I'm moving a small amount of files (1-150 Files, 20 KB each) there are the right amount of threads starting. For each file one thread. As soon as I paste in a larger amount of these files, it's showing that there were more threads started than the directory contains. As you can see, I'm printing out "test" and a counter for each thread started. In the end, the counter is a higher number than the amount of pasted files. The more files I paste, the bigger is the difference between counter and pasted files. Hope you can tell me what I'm doing wrong.
public static void Main(string[] args)
{
Queue queue = new Queue();
queue.Watch();
while (true)
{
}
}
public void Watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "directorypath\\";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
public void OnChanged(object source, FileSystemEventArgs e)
{
WaitForFile(e.FullPath);
thread = new Thread(new ThreadStart(this.start));
thread.Start();
thread.Join();
}
private static void WaitForFile(string fullPath)
{
while (true)
{
try
{
using (StreamReader stream = new StreamReader(fullPath))
{
stream.Close();
break;
}
}
catch
{
Thread.Sleep(1000);
}
}
}
public void start()
{
Console.WriteLine("test" +counter);
counter++;
}
Following this article MSDN, Created
event can solve your problem
The M:System.IO.FileSystemWatcher.OnCreated(System.IO.FileSystemEventArgs) event is raised as soon as a file is created. If a file is being copied or transferred into a watched directory, the M:System.IO.FileSystemWatcher.OnCreated(System.IO.FileSystemEventArgs) event will be raised immediately
public void Watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "directorypath\\";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}