Esempio n. 1
0
        /// <summary>
        /// Executes the task on the action block.
        /// </summary>
        /// <typeparam name="T">the return type of the task</typeparam>
        /// <param name="taskFactory">the function which generates the task to execute</param>
        /// <returns>a task representing the result of the task execution</returns>
        public Task <T> Execute <T>(Func <Task <T> > taskFactory, int priority = 0)
        {
            int depth = 1;

            priority *= 2;

            if (asyncLocalDepth.Value != null)
            {
                priority++;
                depth = asyncLocalDepth.Value.Value + 1;
            }

            tracker.OnStart();
            TaskCompletionSource <T> completionSource = new TaskCompletionSource <T>();

            priorityQueues[priority].Add(new Func <Task>(async() =>
            {
                asyncLocalDepth.Value = new Holder <int>()
                {
                    Value = depth
                };
                try
                {
                    var result = await taskFactory().ConfigureAwait(continueOnCapturedContext: false);

                    tracker.OnComplete();
                    completionSource.SetResult(result);
                }
                catch (OperationCanceledException)
                {
                    tracker.OnComplete();
                    completionSource.SetCanceled();
                }
                catch (Exception ex)
                {
                    tracker.OnComplete();
                    completionSource.SetException(ex);
                }
            }));

            operationBlock.Post(true);

            return(completionSource.Task);
        }
Esempio n. 2
0
 public CompletionHandle(CompletionTracker tracker)
 {
     this.tracker = tracker;
     tracker.OnStart();
 }