2012-11-14 13 views
5

मुझे एक कार्य शेड्यूलर खोजने में कठिनाई हो रही है जिस पर मैं प्राथमिकता वाले कार्यों को निर्धारित कर सकता हूं लेकिन "लपेटा" कार्यों को भी संभाल सकता हूं। यह कुछ ऐसा है जो Task.Run हल करने का प्रयास करता है, लेकिन आप Task.Run पर कोई कार्य शेड्यूलर निर्दिष्ट नहीं कर सकते हैं। मैं कार्य प्राथमिकता आवश्यकता को हल करने के लिए Parallel Extensions Extras Samples से QueuedTaskScheduler का उपयोग कर रहा हूं (इस post द्वारा भी सुझाया गया है)।सीमित समेकन स्तर कार्य शेड्यूलर (कार्य प्राथमिकता के साथ) लपेटे हुए कार्यों को संभालने

class Program 
{ 
    private static QueuedTaskScheduler queueScheduler = new QueuedTaskScheduler(targetScheduler: TaskScheduler.Default, maxConcurrencyLevel: 1); 
    private static TaskScheduler ts_priority1; 
    private static TaskScheduler ts_priority2; 
    static void Main(string[] args) 
    { 
     ts_priority1 = queueScheduler.ActivateNewQueue(1); 
     ts_priority2 = queueScheduler.ActivateNewQueue(2); 

     QueueValue(1, ts_priority2); 
     QueueValue(2, ts_priority2); 
     QueueValue(3, ts_priority2); 
     QueueValue(4, ts_priority1); 
     QueueValue(5, ts_priority1); 
     QueueValue(6, ts_priority1); 

     Console.ReadLine();   
    } 

    private static Task QueueTask(Func<Task> f, TaskScheduler ts) 
    { 
     return Task.Factory.StartNew(f, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.DenyChildAttach, ts); 
    } 

    private static Task QueueValue(int i, TaskScheduler ts) 
    { 
     return QueueTask(async() => 
     { 
      Console.WriteLine("Start {0}", i); 
      await Task.Delay(1000); 
      Console.WriteLine("End {0}", i); 
     }, ts); 
    } 
} 

उदाहरण के विशिष्ट उत्पादन से ऊपर है:

Start 4 
Start 5 
Start 6 
Start 1 
Start 2 
Start 3 
End 4 
End 3 
End 5 
End 2 
End 1 
End 6 

क्या मैं चाहता हूँ है:

Start 4 
End 4 
Start 5 
End 5 
Start 6 
End 6 
Start 1 
End 1 
Start 2 
End 2 
Start 3 
End 3 

संपादित करें:

यहाँ मेरी उदाहरण है

मुझे लगता है कि मैं एक कार्य शेड्यूलर की तलाश में हूं, QueuedTaskScheduler के समान, यह इस समस्या को हल करेगा। लेकिन किसी अन्य सुझाव का स्वागत है।

+0

ठीक है, आप जो चाहते हैं वह कार्यों की प्राथमिकता को संभालना है, लेकिन समानांतर मोड में नहीं चलाया जाता है? क्या आप अपने शेड्यूलर में एक साथ थ्रेड की संख्या को सीमित नहीं कर सकते? – Kek

+0

@Kek 'new QueuedTaskScheduler (targetScheduler: TaskScheduler.Default, maxConcurrencyLevel: 1); उपर्युक्त उपरोक्त है (उपरोक्त धागे की संख्या को 1 तक सीमित करें) –

उत्तर

2

सबसे अच्छा समाधान मैं मिल सकता है QueuedTaskScheduler (Parallel Extensions Extras Samples स्रोत कोड में पाया मूल) के अपने स्वयं के संस्करण बनाने के लिए है।

मैंने QueuedTaskScheduler के रचनाकारों को bool awaitWrappedTasks पैरामीटर जोड़ा।

public QueuedTaskScheduler(
     TaskScheduler targetScheduler, 
     int maxConcurrencyLevel, 
     bool awaitWrappedTasks = false) 
{ 
    ... 
    _awaitWrappedTasks = awaitWrappedTasks; 
    ... 
} 

public QueuedTaskScheduler(
     int threadCount, 
     string threadName = "", 
     bool useForegroundThreads = false, 
     ThreadPriority threadPriority = ThreadPriority.Normal, 
     ApartmentState threadApartmentState = ApartmentState.MTA, 
     int threadMaxStackSize = 0, 
     Action threadInit = null, 
     Action threadFinally = null, 
     bool awaitWrappedTasks = false) 
{ 
    ... 
    _awaitWrappedTasks = awaitWrappedTasks; 

    // code starting threads (removed here in example) 
    ... 
} 

मैं तो संशोधित ProcessPrioritizedAndBatchedTasks() विधि async

private async void ProcessPrioritizedAndBatchedTasks() 

मैं तो बस हिस्सा है जहां निर्धारित कार्य निष्पादित किया जाता है के बाद कोड को संशोधित किया जा करने के लिए:

private async void ProcessPrioritizedAndBatchedTasks() 
{ 
    bool continueProcessing = true; 
    while (!_disposeCancellation.IsCancellationRequested && continueProcessing) 
    { 
     try 
     { 
      // Note that we're processing tasks on this thread 
      _taskProcessingThread.Value = true; 

      // Until there are no more tasks to process 
      while (!_disposeCancellation.IsCancellationRequested) 
      { 
       // Try to get the next task. If there aren't any more, we're done. 
       Task targetTask; 
       lock (_nonthreadsafeTaskQueue) 
       { 
        if (_nonthreadsafeTaskQueue.Count == 0) break; 
        targetTask = _nonthreadsafeTaskQueue.Dequeue(); 
       } 

       // If the task is null, it's a placeholder for a task in the round-robin queues. 
       // Find the next one that should be processed. 
       QueuedTaskSchedulerQueue queueForTargetTask = null; 
       if (targetTask == null) 
       { 
        lock (_queueGroups) FindNextTask_NeedsLock(out targetTask, out queueForTargetTask); 
       } 

       // Now if we finally have a task, run it. If the task 
       // was associated with one of the round-robin schedulers, we need to use it 
       // as a thunk to execute its task. 
       if (targetTask != null) 
       { 
        if (queueForTargetTask != null) queueForTargetTask.ExecuteTask(targetTask); 
        else TryExecuteTask(targetTask); 

        // ***** MODIFIED CODE START **** 
        if (_awaitWrappedTasks) 
        { 
         var targetTaskType = targetTask.GetType(); 
         if (targetTaskType.IsConstructedGenericType && typeof(Task).IsAssignableFrom(targetTaskType.GetGenericArguments()[0])) 
         { 
          dynamic targetTaskDynamic = targetTask; 
          // Here we await the completion of the proxy task. 
          // We do not await the proxy task directly, because that would result in that await will throw the exception of the wrapped task (if one existed) 
          // In the continuation we then simply return the value of the exception object so that the exception (stored in the proxy task) does not go totally unobserved (that could cause the process to crash) 
          await TaskExtensions.Unwrap(targetTaskDynamic).ContinueWith((Func<Task, Exception>)(t => t.Exception), TaskContinuationOptions.ExecuteSynchronously); 
         } 
        } 
        // ***** MODIFIED CODE END **** 
       } 
      } 
     } 
     finally 
     { 
      // Now that we think we're done, verify that there really is 
      // no more work to do. If there's not, highlight 
      // that we're now less parallel than we were a moment ago. 
      lock (_nonthreadsafeTaskQueue) 
      { 
       if (_nonthreadsafeTaskQueue.Count == 0) 
       { 
        _delegatesQueuedOrRunning--; 
        continueProcessing = false; 
        _taskProcessingThread.Value = false; 
       } 
      } 
     } 
    } 
} 

विधि के परिवर्तन ThreadBasedDispatchLoop थोड़ा अलग था, जिसमें हम async कीवर्ड का उपयोग नहीं कर सकते हैं या नहीं तो हम पूर्व की कार्यक्षमता को तोड़ देंगे समर्पित धागे में निर्धारित कार्यों को खारिज करना। तो यहाँ की ThreadBasedDispatchLoop

private void ThreadBasedDispatchLoop(Action threadInit, Action threadFinally) 
{ 
    _taskProcessingThread.Value = true; 
    if (threadInit != null) threadInit(); 
    try 
    { 
     // If the scheduler is disposed, the cancellation token will be set and 
     // we'll receive an OperationCanceledException. That OCE should not crash the process. 
     try 
     { 
      // If a thread abort occurs, we'll try to reset it and continue running. 
      while (true) 
      { 
       try 
       { 
        // For each task queued to the scheduler, try to execute it. 
        foreach (var task in _blockingTaskQueue.GetConsumingEnumerable(_disposeCancellation.Token)) 
        { 
         Task targetTask = task; 
         // If the task is not null, that means it was queued to this scheduler directly. 
         // Run it. 
         if (targetTask != null) 
         { 
          TryExecuteTask(targetTask); 
         } 
         // If the task is null, that means it's just a placeholder for a task 
         // queued to one of the subschedulers. Find the next task based on 
         // priority and fairness and run it. 
         else 
         { 
          // Find the next task based on our ordering rules...          
          QueuedTaskSchedulerQueue queueForTargetTask; 
          lock (_queueGroups) FindNextTask_NeedsLock(out targetTask, out queueForTargetTask); 

          // ... and if we found one, run it 
          if (targetTask != null) queueForTargetTask.ExecuteTask(targetTask); 
         } 

         if (_awaitWrappedTasks) 
         { 
          var targetTaskType = targetTask.GetType(); 
          if (targetTaskType.IsConstructedGenericType && typeof(Task).IsAssignableFrom(targetTaskType.GetGenericArguments()[0])) 
          { 
           dynamic targetTaskDynamic = targetTask; 
           // Here we wait for the completion of the proxy task. 
           // We do not wait for the proxy task directly, because that would result in that Wait() will throw the exception of the wrapped task (if one existed) 
           // In the continuation we then simply return the value of the exception object so that the exception (stored in the proxy task) does not go totally unobserved (that could cause the process to crash) 
           TaskExtensions.Unwrap(targetTaskDynamic).ContinueWith((Func<Task, Exception>)(t => t.Exception), TaskContinuationOptions.ExecuteSynchronously).Wait(); 
          } 
         } 
        } 
       } 
       catch (ThreadAbortException) 
       { 
        // If we received a thread abort, and that thread abort was due to shutting down 
        // or unloading, let it pass through. Otherwise, reset the abort so we can 
        // continue processing work items. 
        if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) 
        { 
         Thread.ResetAbort(); 
        } 
       } 
      } 
     } 
     catch (OperationCanceledException) { } 
    } 
    finally 
    { 
     // Run a cleanup routine if there was one 
     if (threadFinally != null) threadFinally(); 
     _taskProcessingThread.Value = false; 
    } 
} 

मैं इस परीक्षण किया है संशोधित संस्करण है और यह वांछित उत्पादन देता है। इस तकनीक का उपयोग किसी अन्य शेड्यूलर के लिए भी किया जा सकता है। जैसे LimitedConcurrencyLevelTaskScheduler और OrderedTaskScheduler

+0

शेड्यूलर में कार्य पर प्रतीक्षा करना async IO के मान को नष्ट कर देता है। यदि आपको एसिंक आईओ की आवश्यकता नहीं है तो भी आप सिंक्रोनस टास्क निकायों पर स्विच कर सकते हैं। – usr

+0

+1 फिर। मैंने इस सवाल में बहुत कुछ सीखा। पूरी तरह से आश्वस्त नहीं है कि यह समाधान 'AsyncSemaphore' के लिए बेहतर है लेकिन मैं इसके बारे में सोचूंगा। – usr

+0

आप 'टास्कशेड्यूलर 'कार्यान्वयन के भीतर से' async-void' विधि निष्पादित कर रहे हैं? डरावना, मुझे आश्चर्य है कि @StephenCleary टोपी इसके बारे में कुछ भी कहना नहीं है। – springy76

0

मुझे लगता है कि इस लक्ष्य को हासिल करना असंभव है। एक मूल समस्या यह प्रतीत होती है कि TaskScheduler का उपयोग केवल कोड चलाने के लिए किया जा सकता है। लेकिन ऐसे कार्य हैं जो कोड नहीं चलाते हैं, जैसे आईओ कार्य या टाइमर कार्य। मुझे नहीं लगता कि TaskScheduler आधारभूत संरचना का उपयोग उनको निर्धारित करने के लिए किया जा सकता है।

एक TaskScheduler के दृष्टिकोण से यह इस तरह दिखता है:

1. Select a registered task for execution 
2. Execute its code on the CPU 
3. Repeat 

चरण (2) जिसका अर्थ है कि Task शुरू करने और कदम के हिस्से के रूप खत्म करना होगा निष्पादित करने के लिए तुल्यकालिक है (2)। इसका मतलब है कि यह Task async IO नहीं कर सकता क्योंकि यह गैर-अवरुद्ध होगा। उस अर्थ में, TaskScheduler केवल ब्लॉकिंग कोड का समर्थन करता है।

मुझे लगता है कि आपको AsyncSemaphore का संस्करण लागू करके सबसे अच्छा सेवा दी जाएगी जो वेटर्स को प्राथमिकता क्रम में रिलीज़ करती है और थ्रॉटलिंग करती है। आपकी एसिंक विधियां उस गैर-अवरुद्ध तरीके से उस सैफफोर का इंतजार कर सकती हैं। सभी सीपीयू काम डिफ़ॉल्ट थ्रेड-पूल पर चल सकते हैं, इसलिए कस्टम TaskScheduler के अंदर कस्टम थ्रेड शुरू करने की आवश्यकता नहीं है। आईओ कार्य गैर-अवरुद्ध आईओ का उपयोग जारी रख सकते हैं।

+0

जो आपने यहां समझाया है मैंने पहले ही कोशिश की है और यह मूल रूप से एक ही आउटपुट है (मूल समस्या के रूप में)। आपके सुझाव में 'firstPartTask' कतारबद्ध कार्य शेड्यूलर पर निर्धारित है, लेकिन जैसे ही यह पहले' प्रतीक्षा 'को हिट करता है और शेड्यूलर कतार में अगले "पहले भाग" को निष्पादित करता है, भले ही पिछले "आंतरिक कार्य" (पहले 'प्रतीक्षा' के बाद कार्य का रीसेट पूरा नहीं हुआ है। मैं केवल यह सोच सकता हूं कि इसे ** शेड्यूलर ** द्वारा हल किया जाएगा जो इस परिदृश्य को संभालता है जिसे मैं ढूंढ रहा हूं और शेड्यूलर के बाहर कुछ जादू द्वारा हल नहीं किया जा सकता है। –

+0

मुझे विश्वास है कि आप सही हैं। मैंने कुछ विचार और एक सुझाव जोड़ा। मुझे बताओ कि तुम क्या सोचते हो। – usr

+0

आपके अपडेट के लिए धन्यवाद। एक सेमफोर लॉक का उपयोग करके आपका सुझाव बिल्कुल सही है [उपयोगकर्ता] [http://stackoverflow.com/a/13379980/1514235) में उपयोगकर्ता ने सुझाव दिया (मेरी टिप्पणियां देखें)। आपका सुझाव है कि शेड्यूलर केवल अपने कार्यों को सिंक्रनाइज़ रूप से निष्पादित करता है, कुछ हद तक सच है, लेकिन यदि कतार में किसी अन्य कार्य को निष्पादित करने से पहले शेड्यूलर प्रत्येक कार्य के "लिपटे" कार्य का इंतजार कर रहा है। मुझे लगता है कि यह मुझे एक विचार दिया ... धन्यवाद (अगर मैं कुछ के साथ आया तो आपको बताएगा)। –

3

दुर्भाग्य से, यह एक TaskScheduler के साथ हल किया जा सकता है, क्योंकि वे हमेशा Task स्तर पर काम करते हैं, और एक async विधि लगभग हमेशा कई हों Task रों।

आपको प्राथमिकता वाले शेड्यूलर के साथ SemaphoreSlim का उपयोग करना चाहिए। वैकल्पिक रूप से, आप AsyncLock का उपयोग कर सकते हैं (जो मेरे AsyncEx library में भी शामिल है)।

class Program 
{ 
    private static QueuedTaskScheduler queueScheduler = new QueuedTaskScheduler(targetScheduler: TaskScheduler.Default, maxConcurrencyLevel: 1); 
    private static TaskScheduler ts_priority1; 
    private static TaskScheduler ts_priority2; 
    private static SemaphoreSlim semaphore = new SemaphoreSlim(1); 
    static void Main(string[] args) 
    { 
    ts_priority1 = queueScheduler.ActivateNewQueue(1); 
    ts_priority2 = queueScheduler.ActivateNewQueue(2); 

    QueueValue(1, ts_priority2); 
    QueueValue(2, ts_priority2); 
    QueueValue(3, ts_priority2); 
    QueueValue(4, ts_priority1); 
    QueueValue(5, ts_priority1); 
    QueueValue(6, ts_priority1); 

    Console.ReadLine();   
    } 

    private static Task QueueTask(Func<Task> f, TaskScheduler ts) 
    { 
    return Task.Factory.StartNew(f, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.DenyChildAttach, ts).Unwrap(); 
    } 

    private static Task QueueValue(int i, TaskScheduler ts) 
    { 
    return QueueTask(async() => 
    { 
     await semaphore.WaitAsync(); 
     try 
     { 
     Console.WriteLine("Start {0}", i); 
     await Task.Delay(1000); 
     Console.WriteLine("End {0}", i); 
     } 
     finally 
     { 
     semaphore.Release(); 
     } 
    }, ts); 
    } 
} 
+1

यह एक दिलचस्प समाधान की तरह दिखता है। हालांकि, मुझे इसके साथ एक समस्या दिखाई देती है। यद्यपि समाधान (पहले) परिणामस्वरूप सही आउटपुट (जैसा कि इस प्रश्न में) होगा, लेकिन यह निष्पादित कार्यों की प्राथमिकता को तोड़ देगा। शेड्यूलर सभी कार्यों (सही प्राथमिकता में) को तब तक निष्पादित करेगा जब तक कि 'सैमफोर का इंतजार न करें। WaitAsync() 'लेकिन उच्च प्राथमिकता वाले कार्यों को कम प्राथमिकता के कार्यों से पहले लॉक से रिलीज़ नहीं किया जाएगा। यह विशेष रूप से सच है यदि निम्न प्राथमिकता वाले कार्यों को निम्न प्राथमिकता वाले कार्यों के बाद निर्धारित किया गया है (जो अभी भी लॉक से रिलीज़ होने का इंतजार कर रहे हैं)। –

+0

उस स्थिति में, आपको वास्तविक प्राथमिकता-आधारित लॉक की आवश्यकता होगी, जो अस्तित्व में नहीं है क्योंकि AFAIK को किसी और की आवश्यकता नहीं है। आपको अपना खुद का निर्माण करना होगा। –

+0

मैंने अपना खुद का [उत्तर] जोड़ा है (http://stackoverflow.com/a/13414364/1514235)। कृपया एक नज़र डालें और देखें कि आप क्या सोचते हैं। –

संबंधित मुद्दे