Reputation: 4811
I am using a fileSystemWatcher and with Created event listener i am starting a new Thread to process the file contents and do some time consuming operations. The code is like below
fileSystemWatcher = new FileSystemWatcher(folderToWatchFor);
fileSystemWatcher.EnableRaisingEvents = true;
fileSystemWatcher.Created += new FileSystemEventHandler(FileCreated);
private void FileCreated(Object sender, FileSystemEventArgs e)
{
string file_path = e.FullPath;
string file_name = e.Name;
Thread thread = new Thread(() => processFileThread(file_name, file_path));
thread.Start();
//count the active threads here??
}
I like to get the active number of Threads to see how many live threads are there at a time and for this i used
System.Diagnostics.Process.GetCurrentProcess().Threads.Count
But it returned a different counts for me. Like i simply copied 1 file , so only 1 thread is active but the above code returned 23.
So how can i count the active threads started in the function FileCreated()
Upvotes: 2
Views: 5252
Reputation: 1062
The
System.Diagnostics.Process.GetCurrentProcess().Threads.Count
will return all threads for your application. There is no direct possibility to get only your own thread. On top of the operating system threads are the threads of the .net framework itself (due to this the high number of threads).
If you use a static variable be sure to implement locking / interlocked due to multi-threaded access.
private int _threadCounter = 0;
private object _threadCounterLock = new object();
lock(_threadCounterLock)
_threadCounter++;
Upvotes: 2