2012-10-24 27 views
2

這不起作用:如何聲明代碼在主線程中運行?

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

但我只是想知道:

  • 一)是ManagedThreadId保證是1主線程?
  • b)有沒有更好的方法來做到這一點?通過屬性將是最好的我喂。

我正在開發一個Silverlight項目,我沒有標記爲像我不知道它是相關的,但請評論如果你相信Silverlight和其他.net運行時間有區別。

+0

首先,什麼叫 「主線」 是什麼意思?第一個由運行時創建的? –

+0

嘗試下面的線程名稱 - 「UI線程」 – sll

+0

http://stackoverflow.com/questions/2374451/how-to-tell-if-a-thread-is-the-main-thread-in -c-sharp – CodeZombie

回答

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

這個答案在答案日期前2年從Zach Johnson給出的答案中「複製」下來(鏈接如下)!真是個「巧合」。檢查出來: https://stackoverflow.com/questions/2374451/how-to-tell-if-a-thread-is-the-main-thread-in-c-sharp – pongapundit

0

檢查IsBackground屬性。

這可能不是一個完美的解決方案,因爲其他線程可以作爲前臺線程運行,但它可能已足夠。

+0

從MSDN上的文檔看來,主線程以外的線程可能會將'IsBackground'設置爲false:[link](http://msdn.microsoft .com/en-us/library/system.threading.thread.isbackground.aspx) – CalC

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

相關問題