Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to give a temporary name to a thread from the thread pool?

I use Tasks 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?

like image 995
Ilya Kogan Avatar asked May 08 '11 08:05

Ilya Kogan


2 Answers

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.

like image 191
svick Avatar answered Oct 18 '22 17:10

svick


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.

like image 30
Brian Gideon Avatar answered Oct 18 '22 18:10

Brian Gideon