C# 在C中一次计算活动线程数#
我正在使用fileSystemWatcher,并使用创建的事件侦听器启动一个新线程来处理文件内容并执行一些耗时的操作。代码如下所示C# 在C中一次计算活动线程数#,c#,windows,multithreading,C#,Windows,Multithreading,我正在使用fileSystemWatcher,并使用创建的事件侦听器启动一个新线程来处理文件内容并执行一些耗时的操作。代码如下所示 fileSystemWatcher = new FileSystemWatcher(folderToWatchFor); fileSystemWatcher.EnableRaisingEvents = true; fileSystemWatcher.Created += new FileSystemEventHandler(Fi
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??
}
我喜欢获取活动线程数,以查看一次有多少活动线程,为此我使用了
System.Diagnostics.Process.GetCurrentProcess().Threads.Count
但对我来说,结果却不同。就像我只是复制了一个文件,所以只有一个线程是活动的,但是上面的代码返回了23
那么,如何计算函数FileCreated()中启动的活动线程数呢
System.Diagnostics.Process.GetCurrentProcess().Threads.Count
将返回应用程序的所有线程。
没有直接的可能只得到你自己的线程。在操作系统线程之上的是.net framework本身的线程(因此线程数量较多)
如果使用静态变量,请确保由于多线程访问而实现锁定/联锁
private int _threadCounter = 0;
private object _threadCounterLock = new object();
lock(_threadCounterLock)
_threadCounter++;
创建一个静态变量,让每个线程在变量开始时增加一个变量,在变量结束时减少一个变量。@MichaelPuckettII是的,这会起作用。但是想知道.Net framework支持任何这样的功能吗?请检查这个答案。由于.NET framework会自动启动各种后台线程,因此您将获得一个更高的数字。例如,线程池,可能是垃圾收集器的线程池,等等。您是调试代码还是让它自己运行?VisualStudio和调试器将启动几个线程。