【问题标题】:Count the active threads at a time in C#在 C# 中一次计算活动线程
【发布时间】: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 框架支持任何此类功能吗?
  • 检查这个答案。 stackoverflow.com/a/3069769/1356478
  • 您将获得更高的数字,因为 .NET 框架会自动启动各种后台线程。例如。线程池,可能是垃圾收集器等的线程池。
  • 你是调试你的代码还是让它自己运行? Visual Studio 和调试器将启动几个线程。

标签: c# windows multithreading


【解决方案1】:

System.Diagnostics.Process.GetCurrentProcess().Threads.Count

将为您的应用程序返回所有线程。 没有直接的可能性只获得您自己的线程。在操作系统线程之上是 .net 框架本身的线程(因此线程数很高)。

如果您使用静态变量,请务必实现锁定/互锁,因为多线程访问。

private int _threadCounter = 0;
private object _threadCounterLock = new object();

lock(_threadCounterLock)
  _threadCounter++;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-12
    • 2012-01-21
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2010-10-17
    相关资源
    最近更新 更多