【发布时间】:2018-09-01 17:19:32
【问题描述】:
我正在使用 fileSystemWatcher 和 Created 事件侦听器,我正在启动一个新线程来处理文件内容并执行一些耗时的操作。代码如下
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
但它为我返回了不同的计数。就像我只是复制了 1 个文件,所以只有 1 个线程处于活动状态,但上面的代码返回 23。
那么我如何计算函数 FileCreated() 中启动的活动线程
【问题讨论】:
-
创建一个静态变量,让每个线程在启动时将变量加一,在结束时将其减一。
-
@MichaelPuckettII 是的,这会起作用。但是想知道 .Net 框架支持任何此类功能吗?
-
您将获得更高的数字,因为 .NET 框架会自动启动各种后台线程。例如。线程池,可能是垃圾收集器等的线程池。
-
你是调试你的代码还是让它自己运行? Visual Studio 和调试器将启动几个线程。
标签: c# windows multithreading