简体   繁体   中英

How do I assert that the code is running in the main thread?

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM