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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With