Reputation:
I'm using this code to create a new Thread
:
Thread thread = new Thread(delegate()
{
Thread.Sleep(TimeSpan.FromSeconds(delay));
method();
});
thread.Name = identifier;
thread.Start();
I'm trying to loop over the threads and find the thread by its name but i can only get the id from ProcessThread
:
ProcessThreadCollection currentThreads = Process.GetCurrentProcess().Threads;
foreach (ProcessThread thread in currentThreads)
{
// Do whatever you need
}
Any idea how i can get the Thread by the name i initialize?
Upvotes: 0
Views: 7885
Reputation: 1016
In your foreach you are casting your threads array to a System.Diagnostics.ProcessThread
rather than a System.Threading.Thread
, so you are losing some of the properties, such as thread name. Assuming your threads are stored in a List<Thread>();
you can use the following LINQ to get thread with matching identifier name:
var threads = new List<Thread>();
var thread = threads.FirstOrDefault(x => x.Name == identifier);
Or if you need to iterate over your list you can do:
foreach (var thread in currentThreads)
{
// Do whatever you need
}
var
will be inferred as a System.Threading.Thread
EDIT:
What you're trying to do isn't possible. You are throwing away your reference to thread and losing the name as well as the Name property. The .NET managed Thread object is not the same as the operating system ProcessThread object.
You should consider using the Thread ID as your identifier, or as you create new threads, store them in a list, and check the status of thread using thread name on your collection of System.Threading.Thread
.
Upvotes: 2