weston
weston

Reputation: 54781

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:

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.

Upvotes: 3

Views: 3294

Answers (3)

Rohit Vats
Rohit Vats

Reputation: 81243

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

Upvotes: 1

mcalex
mcalex

Reputation: 6778

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

Upvotes: 2

CodeZombie
CodeZombie

Reputation: 5377

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.

Upvotes: 0

Related Questions