2014-04-16 5 views
6

में थ्रेड की सीमा संख्या मेरे पास कुछ सैकड़ों फ़ाइलें हैं जिन्हें मुझे Azure Blob संग्रहण में अपलोड करने की आवश्यकता है।
मैं समांतर कार्य पुस्तकालय का उपयोग करना चाहता हूं।
लेकिन फ़ाइलों की सूची पर एक foreach में अपलोड करने के लिए सभी 100 धागे चलाने के बजाय, मैं थ्रेड की अधिकतम संख्या पर सीमा कैसे लगा सकता हूं और इसका उपयोग समानांतर में नौकरी खत्म कर सकता हूं। या यह स्वचालित रूप से चीजों को संतुलित करता है?कार्य समानांतर लाइब्रेरी

+1

आप का उपयोग नहीं किया जाना चाहिए इसके लिए धागे। इसके लिए 'टास्क'-आधारित एपीआई है, जो स्वाभाविक रूप से असीमित है: [क्लाउडब्लॉकब्लॉब.उप्लोड लोडफाइलएसिंक] (http://msdn.microsoft.com/en-us/library/dn451828.aspx)। क्या आप वीएस -2010 तक सीमित हैं और 'async/await' का उपयोग नहीं कर सकते हैं (इसलिए आपने "सी # 4.0" के साथ प्रश्न टैग किया है)? – Noseratio

+0

यदि मैं सही ढंग से याद करता हूं तो यह उपलब्ध कोर के रूप में कई धागे का उपयोग करेगा। मुझे याद नहीं है कि मैं इसे कहां पढ़ता हूं। शायद एमएस ब्लॉग हो सकता है, या एसओ पर एक जवाब जब मैं गीला सोच रहा था यह आवश्यक है। आप समानांतर उपयोग करके 100 इट्स की एक सूची के साथ परीक्षण परीक्षण में इसे आजमा सकते हैं। – Dbl

+1

@Noseratio VS2010 तक सीमित नहीं है .. मैं भी सी # 5.0 का उपयोग कर सकता हूं .. मुझे टैग के रूप में शामिल करने दें .. – Seenu

उत्तर

9

आपको इसके लिए धागे का उपयोग नहीं करना चाहिए। इसके लिए Task-आधारित एपीआई है, जो स्वाभाविक रूप से असीमित है: CloudBlockBlob.UploadFromFileAsync। समानांतर अपलोड की संख्या को थ्रॉटल करने के लिए async/await और SemaphoreSlim के साथ इसका उपयोग करें।

उदाहरण (untested):

const MAX_PARALLEL_UPLOADS = 5; 

async Task UploadFiles() 
{ 
    var files = new List<string>(); 
    // ... add files to the list 

    // init the blob block and 
    // upload files asynchronously 
    using (var blobBlock = new CloudBlockBlob(url, credentials)) 
    using (var semaphore = new SemaphoreSlim(MAX_PARALLEL_UPLOADS)) 
    { 
     var tasks = files.Select(async(filename) => 
     { 
      await semaphore.WaitAsync(); 
      try 
      { 
       await blobBlock.UploadFromFileAsync(filename, FileMode.Create); 
      } 
      finally 
      { 
       semaphore.Release(); 
      } 
     }).ToArray(); 

     await Task.WhenAll(tasks); 
    } 
} 
2

क्या आपने MaxDegreeOfParallelism का उपयोग करने का प्रयास किया था? इस तरह:

System.Threading.Tasks.Parallel.Invoke(
new Tasks.ParallelOptions {MaxDegreeOfParallelism = 5 }, actionsArray) 
0

आप इस चलाकर पता कर सकते हैं:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var list = new List<int>(); 

     for (int i = 0; i < 100; i++) 
     { 
      list.Add(i); 
     } 

     var runningIndex = 0; 

     Task.Factory.StartNew(() => Action(ref runningIndex)); 

     Parallel.ForEach(list, i => 
     { 
      runningIndex ++; 
      Console.WriteLine(i); 
      Thread.Sleep(3000); 
     }); 

     Console.ReadKey(); 
    } 

    private static void Action(ref int number) 
    { 
     while (true) 
     { 
      Console.WriteLine("worked through {0}", number); 
      Thread.Sleep(2900); 
     } 
    } 
} 

आप देख सकते हैं समानांतरवाद की संख्या शुरू में छोटा होता है, बड़ा हो जाता है, और अंत में छोटे बढ़ता है। तो निश्चित रूप से कुछ प्रकार के स्वचालित अनुकूलन चल रहा है।

0

अनिवार्य रूप से आप संख्या को सीमित, एक कार्य या कार्य प्रत्येक फ़ाइल को अपलोड करने के लिए बनाने के लिए उन्हें एक सूची में डाल दिया, और उसके बाद की प्रक्रिया है कि सूची चाहते करने जा रहे हैं, जिसे समानांतर में संसाधित किया जा सकता है।

My blog post दिखाता है कि यह कार्य और क्रियाओं के साथ दोनों को कैसे करें, और एक नमूना प्रोजेक्ट प्रदान करता है जिसे आप डाउनलोड कर सकते हैं और कार्रवाई में दोनों को देखने के लिए चला सकते हैं।

क्रिया

तो क्रियाओं का उपयोग के साथ, आप में निर्मित नेट Parallel.Invoke फ़ंक्शन का उपयोग कर सकते हैं। यहां हम इसे समानांतर में अधिकतम 5 धागे चलाने के लिए सीमित करते हैं।

var listOfActions = new List<Action>(); 
foreach (var file in files) 
{ 
    var localFile = file; 
    // Note that we create the Task here, but do not start it. 
    listOfTasks.Add(new Task(() => blobBlock.UploadFromFileAsync(localFile, FileMode.Create))); 
} 

var options = new ParallelOptions {MaxDegreeOfParallelism = 5}; 
Parallel.Invoke(options, listOfActions.ToArray()); 

यह विकल्प UploadFromFileAsync की async प्रकृति का इस्तेमाल करते हैं नहीं है, हालांकि, इसलिए आपको नीचे टास्क उदाहरण का उपयोग कर सकते हैं।

कार्य

कार्यों के साथ साथ कोई बिल्ट-इन समारोह है। हालांकि, आप मेरे ब्लॉग पर प्रदान किए गए एक का उपयोग कर सकते हैं।

/// <summary> 
    /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel. 
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para> 
    /// </summary> 
    /// <param name="tasksToRun">The tasks to run.</param> 
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param> 
    /// <param name="cancellationToken">The cancellation token.</param> 
    public static async Task StartAndWaitAllThrottledAsync(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, CancellationToken cancellationToken = new CancellationToken()) 
    { 
     await StartAndWaitAllThrottledAsync(tasksToRun, maxTasksToRunInParallel, -1, cancellationToken); 
    } 

    /// <summary> 
    /// Starts the given tasks and waits for them to complete. This will run the specified number of tasks in parallel. 
    /// <para>NOTE: If a timeout is reached before the Task completes, another Task may be started, potentially running more than the specified maximum allowed.</para> 
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para> 
    /// </summary> 
    /// <param name="tasksToRun">The tasks to run.</param> 
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param> 
    /// <param name="timeoutInMilliseconds">The maximum milliseconds we should allow the max tasks to run in parallel before allowing another task to start. Specify -1 to wait indefinitely.</param> 
    /// <param name="cancellationToken">The cancellation token.</param> 
    public static async Task StartAndWaitAllThrottledAsync(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, int timeoutInMilliseconds, CancellationToken cancellationToken = new CancellationToken()) 
    { 
     // Convert to a list of tasks so that we don't enumerate over it multiple times needlessly. 
     var tasks = tasksToRun.ToList(); 

     using (var throttler = new SemaphoreSlim(maxTasksToRunInParallel)) 
     { 
      var postTaskTasks = new List<Task>(); 

      // Have each task notify the throttler when it completes so that it decrements the number of tasks currently running. 
      tasks.ForEach(t => postTaskTasks.Add(t.ContinueWith(tsk => throttler.Release()))); 

      // Start running each task. 
      foreach (var task in tasks) 
      { 
       // Increment the number of tasks currently running and wait if too many are running. 
       await throttler.WaitAsync(timeoutInMilliseconds, cancellationToken); 

       cancellationToken.ThrowIfCancellationRequested(); 
       task.Start(); 
      } 

      // Wait for all of the provided tasks to complete. 
      // We wait on the list of "post" tasks instead of the original tasks, otherwise there is a potential race condition where the throttler's using block is exited before some Tasks have had their "post" action completed, which references the throttler, resulting in an exception due to accessing a disposed object. 
      await Task.WhenAll(postTaskTasks.ToArray()); 
     } 
    } 

और फिर कार्य की अपनी सूची बनाने और कार्यप्रणाली को कॉल उन्हें चलाने के लिए, एक समय में 5 एक साथ की एक अधिकतम कहना के साथ, आप ऐसा कर सकता है:

var listOfTasks = new List<Task>(); 
foreach (var file in files) 
{ 
    var localFile = file; 
    // Note that we create the Task here, but do not start it. 
    listOfTasks.Add(new Task(async() => await blobBlock.UploadFromFileAsync(localFile, FileMode.Create))); 
} 
await Tasks.StartAndWaitAllThrottledAsync(listOfTasks, 5); 
संबंधित मुद्दे