Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to name a thread in the Visual Studio debugger?

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;
     }
  }
like image 951
greggorob64 Avatar asked Sep 20 '11 20:09

greggorob64


People also ask

How do you name a thread in C#?

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.

How do I view threads in Visual Studio?

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.

How do I debug multiple threads in Visual Studio?

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.


2 Answers

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.

like image 117
Jon Skeet Avatar answered Oct 23 '22 06:10

Jon Skeet


Thread.CurrentThread.Name = "Give your name here";
like image 40
Maxim Avatar answered Oct 23 '22 06:10

Maxim