greggorob64
greggorob64

Reputation: 2557

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;
     }
  }

Upvotes: 7

Views: 1402

Answers (2)

Maxim
Maxim

Reputation: 7348

Thread.CurrentThread.Name = "Give your name here";

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503839

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.

Upvotes: 9

Related Questions