How to enumerate threads in .NET using the Name property?

前端 未结 4 688
-上瘾入骨i
-上瘾入骨i 2021-01-17 10:44

Suppose I start two threads like this:

// Start first thread
Thread loaderThread1 = new Thread(loader.Load);
loaderThread1.Name = \"Rope\";
loaderThread1.Sta         


        
相关标签:
4条回答
  • 2021-01-17 10:56

    I suspect you might have to put the threads into a Dictionary<string,Thread> for that to work - but why do you want it anyway? There are usually other ways of communicating between threads (any of the lock / wait objects).

    To work at the process level (i.e. not thinking of the Thread object), see here - you could limit it to the current process, but you won't be able to interact with the thread.

    0 讨论(0)
  • 2021-01-17 11:17

    Note also that thread names are not required to be unique. Seems like using the thread ID might be a better option...

    0 讨论(0)
  • 2021-01-17 11:20

    So, after my mistake with the process threads, here a way how to hold your Threads. Nothing spectacular, but I think coding examples are very handy anytime.

    List<Thread> threads = new List<Thread>();
    
    for (int i = 0; i < 10; i++)
    {
    
        Thread t = new Thread(delegate()
            {
            do
            {
                Thread.Sleep(50);
            } while (true);
            });
    
        t.IsBackground = true;
        t.Name = i.ToString();
        t.Start();
        threads.Add(t);
    }
    
    foreach (Thread t in threads)
    {
        Console.WriteLine(t.Name);
    }
    
    0 讨论(0)
  • 2021-01-17 11:23

    I think you want the following

    System.Diagnostics.Process.GetCurrentProcess().Threads

    0 讨论(0)
提交回复
热议问题