如何断言代码在主线程中运行?

时间:2012-10-24 11:41:40

标签: c#

这不起作用:

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

这确实有效:

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

但我只是想知道:

  • a)主线程的ManagedThreadId保证为1吗?
  • b)有更好的方法吗?通过属性将是我最好的。

我正在开发一个Silverlight项目,我没有标记,因为我不知道它是否相关,但请注意,如果您相信Silverlight和其他.net运行时之间存在差异。

3 个答案:

答案 0 :(得分:2)

Thread.CurrentThread.Name仅在设置名称时有效。我的猜测是调试器提供了一个默认名称。你可以设置线程的名称(在创建时,或者一旦你命中main,可能)?这样你可以检查断言。

类似的东西:

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

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

答案 1 :(得分:2)

将此代码放在应用程序的entry方法中 -

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

答案 2 :(得分:0)

检查IsBackground属性。

这可能不是一个完美的解决方案,因为其他线程可以作为前台线程运行,但它可能足够了。