Is it possible to give a temporary name to a thread from the thread pool?
I use Task
s to run asynchronous operations in .NET.
In order to make a better use of the Threads debugging window, I would like to identify the currently running task by a thread name. However, the Name
property of each thread can only be set once. So the second 开发者_运维技巧time the same thread from the pool is used, I'm getting a runtime exception.
Is there any way to get around this?
When you schedule your tasks with the TaskCreationOptions.LongRunning
, it runs on its own thread, not a thread from the ThreadPool, so you can safely set the thread's name.
Using this method will probably have performance impact, so I would suggest using it only during debugging. Also, it seems the number of threads created this way isn't limited (apart from the global limits on number of threads), so it won't behave the same as without using this option.
Is there any way to get around this?
Well, technically yes. I mean you could use reflection to set the name. See my answer here for how to do it. Naturally, I do not recommend setting private fields via reflection for production code, but I suppose you can get away with it since you only want to use it for debugging.
As Ani notes in his comment: Parallel Tasks Window will give you details of the state of all existing Tasks. This, and the Parallel Stacks, tools window will give better detail for most debugging of tasks.
Is it possible to give a temporary name to a thread from the thread pool?
Thread.Name
allows you to set a thread's name, but (if I recall correctly) this can only be set once for a single thread rather limiting its usefulness for thread pool threads (tasks run on thread pool threads).
You can always name the thread in the moment that the thread start with Thread.CurrentThread.Name.
//this is how you put the thread in the ThreadPool.
ThreadPool.QueueUserWorkItem(new WaitCallback(this.Handler), this);
//this is how you name the Thread
void Handler(object parameters)
{
Thread.CurrentThread.Name = "MyThreadName";
while(true)
{
}
}
精彩评论