Can I give a temporary name to a thread from a thread pool?

I use Task to run asynchronous operations in .NET.

To better use the Threads debug window, I would like to identify the currently running task by the name of the thread. However, the Name property for each thread can only be set once. So, the second time the same thread from the pool is used, I get an exception at runtime.

Is there any way around this?

+6
source share
4 answers

As Ani notes in his comment: The Parallel Tasks window will give you information on the status of all existing tasks. This is also a window of parallel stacks, a tool window will give more detailed information for most of the debugging tasks.

Can I specify a temporary stream name from a thread pool?

Thread.Name allows Thread.Name to set the name of the thread, but (if I call it right), it can be set only once for one thread rather limits its usefulness for thread pool threads (tasks are performed in thread pool threads).

+1
source

When you plan your tasks using TaskCreationOptions.LongRunning , it starts in its thread, not in the thread from ThreadPool, so you can safely set the thread name.

Using this method is likely to affect performance, so I would suggest using it only during debugging. In addition, it seems that the number of threads created in this way is unlimited (except for the global restrictions on the number of threads), so it will not behave the same as without using this option.

+4
source

Is there any way around this?

Well, technically yes. I mean, you can use reflection to set a name. See my answer here on how to do this. Naturally, I do not recommend setting up private fields using reflection for production code, but I assume that you will succeed because you want to use it for debugging.

+2
source

You can always name a thread at the moment when the thread starts 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) { } } 
0
source

Source: https://habr.com/ru/post/887544/


All Articles