2012-11-14 25 views
5

優先度の高いタスクをスケジュールすることができますが、「ラップされた」タスクも処理できるタスクスケジューラを見つけるのは苦労しています。 Task.Runが解決しようとするものですが、Task.Runにタスクスケジューラを指定することはできません。 私はParallel Extensions Extras SamplesQueuedTaskSchedulerを使用して、タスクの優先度の要件を解決しました(これは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 

EDIT:

私はこの問題を解決するQueuedTaskSchedulerに似たタスクスケジューラを探していると思います。しかし、他の提案は大歓迎です。

+0

さて、あなたが望むのは、タスクの優先度を処理することですが、並列モードでは実行しません。あなたのスケジューラーの同時スレッドの数を制限するだけではいけませんか? – Kek

+0

@Kek '新しいQueuedTaskScheduler(targetScheduler:TaskScheduler.Default、maxConcurrencyLevel:1);上記は正確です(同時スレッドの数を1に制限してください) –

答えて

2

私は見つけることができる最善の解決策は、QueuedTaskSchedulerParallel 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) 
    ... 
} 

Iは、私はその後、ちょうどスケジュールされたタスクを実行する部分の後のコードを変更しasync

private async void ProcessPrioritizedAndBatchedTasks() 

ことが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キーワードを使用できないという点で少し違っていました。そうしないと、ex専用スレッドでスケジュールされたタスクをエコーする。だからここに私はこれをテストしている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; 
    } 
} 

の修正版であり、それは所望の出力を提供します。この技術は他のスケジューラーにも使用できます。例えば。 LimitedConcurrencyLevelTaskSchedulerOrderedTaskScheduler

+0

スケジューラでタスクを待機すると、async IOの値が破棄されます。とにかく非同期IOが必要ない場合は、同期タスク本体に切り替えることができます。 – usr

+0

+1。私はこの質問で多くを学んだ。このソリューションが 'AsyncSemaphore'よりも好ましいとは確信していませんが、私はそれについて考えるでしょう。 – usr

+0

'TaskScheduler'実装の中から' async-void'メソッドを実行していますか?怖い、私は@StephenClearyはこれについて何も言わない帽子が不思議です。 – springy76

0

私はこの目標を達成することは不可能だと思います。コアの問題は、TaskSchedulerはコードを実行するためにしか使用できないように思われる。しかし、IOタスクやタイマータスクなど、コードを実行しないタスクがあります。私は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を自分で実装することで、最高のサービスを提供できると思います。あなたの非同期メソッドは、セマフォをノンブロッキングの方法で待つことができます。すべてのCPU作業はデフォルトのスレッドプール上で実行できるので、カスタムの内部でカスタムスレッドを開始する必要はありませんTaskScheduler。 IOタスクは、ノンブロッキングIOを引き続き使用できます。彼らは常にTaskレベルで動作し、async方法はほとんど常に複数のTask Sが含まれているため

+0

ここで説明したことは、すでに試したもので、基本的には同じ出力です元の問題のように)。あなたの提案では、 'firstPartTask'はキューに入れられたタスクスケジューラでスケジューリングされますが、最初の' await'にヒットするとすぐに完了し、スケジューラは単に前の "内部タスク"(最初の 'await'の後のタスクのリセット)は完了していません。私はこれが私が探しているこのシナリオを処理する**スケジューラ**によって解決されると思うだけで、スケジューラ以外のいくつかの魔法によって解決することはできません。 –

+0

私はあなたが正しいと信じるようになりました。私はいくつかの考えと示唆を加えました。あなたの考えを教えてください。 – usr

+0

ありがとうございます。セマフォーロックを使用するあなたの提案は、ユーザーが以下の[回答](http://stackoverflow.com/a/13379980/1514235)で提案したとおりです(私のコメントを参照)。スケジューラーがタスクを同期して実行するだけでは、キュー内の他のタスクを実行する前にスケジューラーが各タスクの「ラップされた」タスクを待っている場合はどうなるでしょうか。私はこれが私に考えを与えたと思う...ありがとう(私が何かを思い付くかどうかを知らせる)。 –

3

は残念ながら、これは、TaskSchedulerで解決することはできません。

優先度スケジューラと組み合わせて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

これは興味深い解決策のようです。しかし、これには1つの問題があります。ソリューションは(最初は)正しい結果を出すでしょうが(この質問のように)、実行されたタスクの優先順位を破ります。スケジューラは 'await semaphore.WaitAsync()'が実行されるまで(正しい優先度で)すべてのタスクを実行しますが、優先度の高いタスクは優先度の低いタスクの前にロックから解放されません。優先度の高いタスク(ロックから解放されるのをまだ待っている)が優先度の低いタスクの後にスケジュールされている場合、これは特に当てはまります。 –

+0

その場合、AFAIKは誰も必要としていないため、存在しない実際の優先順位ベースのロックが必要になります。あなたは自分でビルドする必要があります。 –

+0

私は自分の[回答](http://stackoverflow.com/a/13414364/1514235)を追加しました。見て、あなたの考えを見てください。 –

関連する問題