I'm working in C# 4.0 (winforms), debugging an application with 10+ threads. While debugging, there is a drop down to select which thread I should be debugging (only accessible during a breakpoint).
These show up as "Win32 Thread", "Worker Thread", "RPC Callback Thread", etc...
I'd love to name them from within my code. I'm running all my threads via background workers.
Edit: my solution. This may not work 100% of the time, but it does exactly what it needs to. If the labels are wrong in some case, thats OK in the context I'm working with.
At every backgroundworker's *_dowork event, I put the following line of code in:
ReportData.TrySetCurrentThreadName(String.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType, MethodBase.GetCurrentMethod().Name));
Which is...
public static void TrySetCurrentThreadName(String threadName)
{
if (System.Threading.Thread.CurrentThread.Name == null)
{
System.Threading.Thread.CurrentThread.Name = threadName;
}
}
In C#, a user is allowed to assign a name to the thread and also find the name of the current working thread by using the Thread.Name property of the Thread class. Here, the string contains the name of the thread or null if no name was assigned or set.
To display the Threads window in break mode or run mode While Visual Studio is in debug mode, select the Debug menu, point to Windows, and then select Threads.
Yes. In the Threads window (Debug -> Windows -> Threads) right-click the thread you want and select "switch to thread". You can also choose "freeze" on the threads you don't want to debug in order to keep them from running. Don't forget to "thaw" them if you expect them to do work, however.
Well you can use the Thread.Name property, but you can only write to it once - so when you create the thread, give it an appropriate name.
Thread.CurrentThread.Name = "Give your name here";
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