2011-09-29 8 views
4

는 내가 CLR이 작동 각 AppDomainThreadPool 타임 슬라이스를 제공 것을 알고있다, 그러나 나는 경우는 CLR에 의해 또는 AppDomin ThreadPool을에 의해 관리되도록 Thread t = new Thread(...);스레드는 스레드 풀에서 관리합니까?

같은 새로운 스레드를 생성하여 알고 싶어?

답변

3

Thread 클래스로 스레드를 만들면 이 제어됩니다. 필요에 따라 파일을 만들고 사용자가 background or foreground (호출 프로세스를 활성 상태로 유지)인지 여부를 정의하고 Priority을 설정하면 시작하고 중지합니다.

는 (뒤에서 ThreadPool 사용) ThreadPool 또는 Task 사용하면 ThreadPool 클래스는 스레드의 생성을 관리 할 수 ​​있도록, 당신에게 새로운 스레드를 생성하는 데 필요한 시간을 절약 할 스레드의 재사용 성을 극대화 할 수 있습니다. 한 가지주의 할 점은 Thread 기본값과 달리 ThreadPool에 의해 생성 된 스레드는 호출 프로세스를 활성 상태로 유지하지 않는다는 것입니다.

ThreadPool을 사용하면 큰 이점이 있습니다. 적은 수의 스레드가 많은 작업을 처리 할 수 ​​있다는 것입니다. 반대로 풀이 재사용을 위해 설계 되었기 때문에 풀을 죽이지 않는다는 가정하에 ThreadPool으로 생성 된 스레드가 많지만 나중에 항목 수가 줄어들면 ThreadPool이 많이 유휴 상태가되어 리소스를 낭비합니다.

6

Thread t = new Thread();ThreadPool으로 관리하지 않습니다. 그러나 CLR이 운영 체제 스레드에서 제공하는 추상화입니다. ThreadPool은 스레드 재사용과 스레드 자원 공유를 용이하게하는 추가 추상화입니다. http://www.albahari.com/threading/

당신이 .NET 4.0을 사용하는 경우가 TPL을 사용하는 것이 좋습니다 :

여기에 .NET 스레드에 훌륭한 자원이다.

+0

을 넣어. 이제 질문은 내가 그를 수정합니까 :) – guyl

+0

굉장 링크, 고마워! –

1

새 스레드를 만들면 스레드 풀에서 관리하는 이 아닌이됩니다.

1

스레드를 수동으로 만든 다음 수명을 제어하는 ​​경우 스레드 풀과 독립적입니다.

0

다음 예제는 스레드 풀을 사용하는 방법을 보여줍니다. 먼저 스레드 풀이 모든 작업 항목 실행을 완료했음을 프로그램이 알 수 있도록 ManualResetEvent 객체를 만듭니다. 그런 다음 스레드 풀에 하나의 스레드를 추가하려고 시도합니다. 이 작업이 성공하면 나머지 작업이 추가됩니다 (이 예제에서는 4 개). 스레드 풀은 작업 항목을 사용 가능한 스레드에 넣습니다. eventX.Set 메서드를 사용하여 이벤트가 트리거 될 때까지 나머지 프로그램을 대기하게하는 eventX의 WaitOne 메서드가 호출됩니다. 마지막으로, 프로그램은 스레드에서로드 (특정 작업 항목을 실제로 실행하는 스레드)를 인쇄합니다.

// SimplePool.cs 
// Simple thread pool example 
using System; 
using System.Collections; 
using System.Threading; 

// Useful way to store info that can be passed as a state on a work item 
public class SomeState 
{ 
    public int Cookie; 
    public SomeState(int iCookie) 
    { 
     Cookie = iCookie; 
    } 
} 

public class Alpha 
{ 
    public Hashtable HashCount; 
    public ManualResetEvent eventX; 
    public static int iCount = 0; 
    public static int iMaxCount = 0; 
    public Alpha(int MaxCount) 
    { 
     HashCount = new Hashtable(MaxCount); 
     iMaxCount = MaxCount; 
    } 

    // Beta is the method that will be called when the work item is 
    // serviced on the thread pool. 
    // That means this method will be called when the thread pool has 
    // an available thread for the work item. 
    public void Beta(Object state) 
    { 
     // Write out the hashcode and cookie for the current thread 
     Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(), 
     ((SomeState)state).Cookie); 
     // The lock keyword allows thread-safe modification 
     // of variables accessible across multiple threads. 
     Console.WriteLine(
     "HashCount.Count=={0}, Thread.CurrentThread.GetHashCode()=={1}", 
     HashCount.Count, 
     Thread.CurrentThread.GetHashCode()); 
     lock (HashCount) 
     { 
     if (!HashCount.ContainsKey(Thread.CurrentThread.GetHashCode())) 
      HashCount.Add (Thread.CurrentThread.GetHashCode(), 0); 
     HashCount[Thread.CurrentThread.GetHashCode()] = 
      ((int)HashCount[Thread.CurrentThread.GetHashCode()])+1; 
     } 

     // Do some busy work. 
     // Note: Depending on the speed of your machine, if you 
     // increase this number, the dispersement of the thread 
     // loads should be wider. 
     int iX = 2000; 
     Thread.Sleep(iX); 
     // The Interlocked.Increment method allows thread-safe modification 
     // of variables accessible across multiple threads. 
     Interlocked.Increment(ref iCount); 
     if (iCount == iMaxCount) 
     { 
     Console.WriteLine(); 
     Console.WriteLine("Setting eventX "); 
     eventX.Set(); 
     } 
    } 
} 

public class SimplePool 
{ 
    public static int Main(string[] args) 
    { 
     Console.WriteLine("Thread Pool Sample:"); 
     bool W2K = false; 
     int MaxCount = 10; // Allow a total of 10 threads in the pool 
     // Mark the event as unsignaled. 
     ManualResetEvent eventX = new ManualResetEvent(false); 
     Console.WriteLine("Queuing {0} items to Thread Pool", MaxCount); 
     Alpha oAlpha = new Alpha(MaxCount); // Create the work items. 
     // Make sure the work items have a reference to the signaling event. 
     oAlpha.eventX = eventX; 
     Console.WriteLine("Queue to Thread Pool 0"); 
     try 
     { 
     // Queue the work items, which has the added effect of checking 
     // which OS is running. 
     ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta), 
      new SomeState(0)); 
     W2K = true; 
     } 
     catch (NotSupportedException) 
     { 
     Console.WriteLine("These API's may fail when called on a non-Windows 2000 system."); 
     W2K = false; 
     } 
     if (W2K) // If running on an OS which supports the ThreadPool methods. 
     { 
     for (int iItem=1;iItem < MaxCount;iItem++) 
     { 
      // Queue the work items: 
      Console.WriteLine("Queue to Thread Pool {0}", iItem); 
      ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),new SomeState(iItem)); 
     } 
     Console.WriteLine("Waiting for Thread Pool to drain"); 
     // The call to exventX.WaitOne sets the event to wait until 
     // eventX.Set() occurs. 
     // (See oAlpha.Beta). 
     // Wait until event is fired, meaning eventX.Set() was called: 
     eventX.WaitOne(Timeout.Infinite,true); 
     // The WaitOne won't return until the event has been signaled. 
     Console.WriteLine("Thread Pool has been drained (Event fired)"); 
     Console.WriteLine(); 
     Console.WriteLine("Load across threads"); 
     foreach(object o in oAlpha.HashCount.Keys) 
      Console.WriteLine("{0} {1}", o, oAlpha.HashCount[o]); 
     } 
     return 0; 
    } 
} 

아웃 내가 스레드가 스레드에 의해 관리되지 않는 팀 리더는 내가 잘못했다라고 말했다 면접에서 닷넷 4 을 사용하고

Thread Pool Sample: 
Queuing 10 items to Thread Pool 
Queue to Thread Pool 0 
Queue to Thread Pool 1 
... 
... 
Queue to Thread Pool 9 
Waiting for Thread Pool to drain 
98 0 : 
HashCount.Count==0, Thread.CurrentThread.GetHashCode()==98 
100 1 : 
HashCount.Count==1, Thread.CurrentThread.GetHashCode()==100 
98 2 : 
... 
... 
Setting eventX 
Thread Pool has been drained (Event fired) 

Load across threads 
101 2 
100 3 
98 4 
102 1 
관련 문제