3

This doesn't work:

Debug.Assert(Thread.CurrentThread.Name == "Main Thread"); //doesn't work
                     //name is null despite name
                     //in debugger being "Main Thread"

This does work:

Debug.Assert(Thread.CurrentThread.ManagedThreadId == 1);

But I was just wondering:

  • a) Is ManagedThreadId guaranteed to be 1 for the Main Thread?
  • b) Is there a better way of doing this? Via Attribute would be neatest I feed.

I'm working on a Silverlight project, I haven't tagged as such as I don't know it's relevant, but please comment if you belive there is a difference between Silverlight and other .net runtimes.

weston
  • 54,145
  • 21
  • 145
  • 203

3 Answers3

2

Thread.CurrentThread.Name only works if the name was set. My guess is the debugger provides a default name. Can you set the name of the thread (at creation, or as soon as you hit main, perhaps)? This way you can check the assertion.

Something like:

static void Main()
{
    // Check whether the thread has previously been named 
    // to avoid a possible InvalidOperationException. 
    if(Thread.CurrentThread.Name == null)
    {
        Thread.CurrentThread.Name = "MainThread";
    }
}

See: http://msdn.microsoft.com/en-us/library/system.threading.thread.name.aspx

mcalex
  • 6,628
  • 5
  • 50
  • 80
1

Put this code in your entry method of an application -

static int mainThreadId;

// In Main method:
mainThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

// If called in the non main thread, will return false;
public static bool IsMainThread
{
    get
    {
       return System.Threading.Thread.CurrentThread.ManagedThreadId
                                                == mainThreadId;
    }
}
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • 3
    This answer is "copied" from answer given by Zach Johnson here (link below) 2 years before your answer-date! What a "coincidence". Check it out: https://stackoverflow.com/questions/2374451/how-to-tell-if-a-thread-is-the-main-thread-in-c-sharp – Gsv Jul 20 '17 at 02:21
0

Check the IsBackground property.

This might not be a perfect solution as other threads can run as foreground threads, but it might be sufficient enough.

CodeZombie
  • 5,367
  • 3
  • 30
  • 37
  • From the documentation on MSDN it appears threads other than the main thread could have the 'IsBackground' set to false: [link](http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx) – SpruceMoose Oct 24 '12 at 11:51