2013-06-14 2 views
0

스레딩을 사용하여 Sharepoint에서 여러 파일을 동시에 다운로드하는 간단한 프로그램을 작성했습니다. Do While Loop를 사용하여 대기열이 가득 찰 때마다 프로그램이 대기하는지 확인했습니다.C# Sharepoint에서 여러 파일을 다운로드하기위한 대기 대기 스레드 대기열 (대기열이 가득 찰 때까지 대기)

아래의 내 의견을 참조하십시오. 대기열이 가득 찰 때마다 프로그램이 대기 할 수있는보다 효율적인 방법을 찾고 있습니다. Do While 루프를 사용하면 내 프로그램의 CPU 사용량이 70 %가되고 Thread.Sleep (1000)을 추가하면 CPU 사용량이 30 %로 줄어들지 만 더 효율적인 방법이 있어야하며 열? 이 보인다

// Main Program to dispatch Threads to download files from Sharepoint 
bool addedtoDownloader; 
        do 
        { 
         addedtoDownloader = ThreadDownloader.addJob(conn, item.FileRef, LocalFolderPath); 

         // ===== by having the following 2 lines below reduce CPU usage 
          if (addedtoDownloader == false) 
          System.Threading.Thread.Sleep(1000); 
         // ====== Is there a better way to do this? ================ 
        } 
        while (addedtoDownloader == false); 





class ThreadDownloader 
{ 
    public const int MaxThread = 15; 

    public static List<Thread> ThreadList = new List<Thread>(); 


    public static bool addJob(ClientContext conn, string SrcFileURL, string DestFolder) 
    { 
     RefreshThreadList(); 

     if (ThreadList.Count() < MaxThread) 
     { 

      Thread t = new Thread(() => Program.DownloadFile(conn, SrcFileURL, DestFolder)); 
      ThreadList.Add(t); 
      t.Start(); 
      return true; 
     } 

     return false; 


    } 

    public static void RefreshThreadList() 
    { 
     List<Thread> aliveThreadList = new List<Thread>(); 

     foreach (var t in ThreadList) 
     { 
      if (t.IsAlive) 
      { 
       aliveThreadList.Add(t); 
      } 
     } 

     ThreadList.Clear(); 
     ThreadList = aliveThreadList; 
    } 



} 
+1

사용하십시오 ['BlockingCollection'] (http://msdn.microsoft.com/en-us/library/ dd267312.aspx) - 이름에서 알 수 있듯이, 이런 종류의 작업을 위해 설계되었습니다. –

답변

0

감사 세마포어에 대한 좋은 사용의 경우 :

private static SemaphoreSlim semaphore = new SemaphoreSlim(MaxThread); 

public static void addJob(ClientContext conn, string SrcFileURL, string DestFolder) 
{ 
    semaphore.Wait(); 

    RefreshThreadList(); 

    Thread t = new Thread(() => 
     { 
      try 
      { 
       Program.DownloadFile(conn, SrcFileURL, DestFolder); 
      } 
      finally 
      { 
       semaphore.Release(); 
      } 
     }); 
    ThreadList.Add(t); 
    t.Start(); 
} 
+0

고마워 Pragmateek,하지만 .net 3.5 만 사용한다면 어떨까요? – user2486348

+0

도이 경우 ThreadList가 더 이상 필요하지 않다고 생각합니까? – user2486348

+0

3.5로 고생했다면 좋은 오래된 세마포어 클래스를 사용하십시오. 그리고 네, 스레드 목록을 제거 할 수 있다고 생각합니다. :) – Pragmateek