2012-10-24 5 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); 

하지만 난 그냥 궁금 해서요 :

  • a)는 메인 스레드에 대한 1을 보장 ManagedThreadId인가 ?
  • b) 이렇게하는 더 좋은 방법이 있습니까? 속성을 통해 가장 깨끗한 피드 것입니다.

저는 Silverlight 프로젝트에서 작업하고 있습니다. 관련이 있는지 모를만큼 태그가 지정되지 않았지만, Silverlight와 다른 .net 런타임 사이에는 차이가 있다고 생각한다면 의견을 말하십시오.

+0

먼저, "메인 스레드"가 무엇을 의미합니까? 런타임에 의해 처음으로 생성됩니까? –

+0

다음의 스레드 이름을 사용해보세요 -''UI Thread "' – 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

이 답변은 자크 존슨의 답변 (아래 링크)에서 "복사"되었습니다. 이런 우연이". 그것을 확인하십시오 : 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이 작동합니다. 내 생각에 디버거는 기본 이름을 제공합니다. 스레드의 이름을 설정할 수 있습니까 (작성시, 또는 메인을 누르 자마자)? 이렇게하면 주장을 확인할 수 있습니다.

뭔가 같은 :

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

관련 문제