2012-09-27 23 views
1

我有一個函數。我想通過不同的線程多次調用這個函數。我怎樣才能做到這一點 ?。我的功能是低於由不同線程調用函數的問題

public void DownloadImage(List<String> imageUrl) 
    { 
     imageCount = imageUrl.Count; 

     foreach (string url in imageUrl) 
     { 
      StartDownload(url); 
     } 
    } 

我有10個可供下載的圖像。我正在使用webclient下載圖像。所以我想通過10個線程來調用這個函數。我怎樣才能做到這一點 ?

我試過下面的代碼。但它顯示編譯錯誤

ParameterizedThreadStart starter; 

     for (int i = 0; i < 10; i++) 
     { 
      _imageDownloader = new ImageDownloader(); //this is class where I defined the function above ie DownloadImage 
      _imageDownloader.OnCompleted+=new Completed(_imageDownloader_OnCompleted); 
      starter = new ParameterizedThreadStart(_imageDownloader.DownloadImage); // in this line it showing a compile error "No overload for 'DownloadImage' matches delegate 'System.Threading.ParameterizedThreadStart'" 
      Thread imageThread = new Thread(starter); 
      imageThread.Start(); 
     } 

請幫助。

回答

2

您可以使用任務並行庫:

public void DownloadImage(List<String> imageUrl) 
{ 
    Parallel.ForEach(imageUrl, url => StartDownload(url)); 
}