【问题标题】:Check if any threads remain at end of test检查测试结束时是否有任何线程
【发布时间】:2019-10-28 00:41:19
【问题描述】:

有没有办法检查是否有任何“用户”线程正在运行。我想把它放在[TestCleanup] 方法中,如果测试没有加入它启动的所有线程,则测试失败。

我认为仅仅列出所有当前正在运行的线程并没有帮助,例如,可能有一些垃圾收集线程在不确定的时间开始。所以我基本上想要不只是与运行时相关联的线程。

【问题讨论】:

  • 而且您肯定使用的是线程而不是任务,对吧?
  • 在当前代码库中是
  • 这个测试似乎指向更大的问题,这不应该真的需要测试,如果你这样做,它可能应该在另一个测试中涵盖
  • 我不明白你的意思,我想在所有测试中涵盖这一点。它可能是也可能不是启动线程的测试代码,但无论哪种情况,一旦测试完成,它们都应该被清理。如果不是,这似乎是我们应该注意的事情,因此测试应该失败。
  • 如果你能分享一个minimal reproducible example,那就太棒了。

标签: c# .net multithreading


【解决方案1】:

我建议您查看 Microsoft.Diagnostics.Runtime 库 (Nuget)。特别是 CLR 功能。您可以使用以下代码获取具有堆栈跟踪的所有线程的列表

using (DataTarget target = DataTarget.AttachToProcess(Process.GetCurrentProcess().Id, 5000, AttachFlag.Passive))
{
    ClrRuntime runtime = target.ClrVersions.First().CreateRuntime();
    return new runtime.Threads;
}

【讨论】:

    【解决方案2】:

    问题的 cmets 部分有一些非常有效的观点,但你可以

    1. 试试看线程计数是否适合你,而不必担心
    2. 试试TryStartNoGCRegion:
      GC.TryStartNoGCRegion(1024*1204*10);
      var count = System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
      GC.EndNoGCRegion();
      

    这是一个简单的例子。

    public static void Main()
    {
        int GetThreadCount() {
            GC.TryStartNoGCRegion(1024*1204*10);
            var count = System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
            GC.EndNoGCRegion();
            return count;
        }
    
    
        var count1 = GetThreadCount();
        Console.WriteLine($"Headcount at (in?) the beginning: {count1}");
    
        var t1 = new Thread(() => {       
                Thread.Sleep(1000);
            });
        t1.Start();
    
        var count2 = GetThreadCount();
        Console.WriteLine($"Headcount later: {count2}");
    
        if (count2 != count1 ) {
            Console.WriteLine("Oh no! Threads running!");
        }
    
        t1.Join();
    
        var count3 = GetThreadCount();
        Console.WriteLine($"Headcount even later: {count3}");
    
        if (count3 != count1 ) {
            Console.WriteLine("Oh no! Threads running!");
        } else {
                Console.WriteLine("Phew. Everybody Joined the party.");
        }
    
        Console.ReadLine();
    }
    

    输出

    // .NETCoreApp,Version=v3.0
    Headcount at (in?) the beginning: 10
    Headcount later: 11
    Oh no! Threads running!
    The thread 9620 has exited with code 0 (0x0).
    Headcount even later: 10
    Phew. Everybody Joined the party.
    

    【讨论】:

    • 这是个好主意。我会试一试,看看它在测试套件中的一致性。
    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    相关资源
    最近更新 更多