public static void UsingTaskFactory()
        {
            Task<Int32[]> parent = Task.Run(() =>
            {
                var result = new Int32[3];

                TaskFactory tf = new System.Threading.Tasks.TaskFactory(TaskCreationOptions.AttachedToParent,
                    TaskContinuationOptions.ExecuteSynchronously);

                tf.StartNew(() => result[0] = 0);
                tf.StartNew(() => result[1] = 1);
                tf.StartNew(() => result[2] = 2);
                return result;

            });

            var finalTask = parent.ContinueWith(
              ParentTask =>
              {
                  foreach (int i in ParentTask.Result)
                  {
                      Console.WriteLine(i);
                  }
              });
            finalTask.Wait();
        }
Beispiel #2
0
        public static TResult RunSync <TResult>(Func <Task <TResult> > func)
        {
            var cultureUi = CultureInfo.CurrentUICulture;
            var culture   = CultureInfo.CurrentCulture;

            return(taskFactory.StartNew(() =>
            {
                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = cultureUi;
                return func();
            }).Unwrap().GetAwaiter().GetResult());
        }
Beispiel #3
0
        /// <summary>
        /// Creates and starts a task.
        /// </summary>
        public static SystemTask StartNew(SystemTaskFactory factory, Action action, SystemCancellationToken cancellationToken)
        {
            var runtime = CoyoteRuntime.Current;

            if (runtime.SchedulingPolicy is SchedulingPolicy.None)
            {
                return(factory.StartNew(action, cancellationToken));
            }

            return(runtime.TaskFactory.StartNew(action, cancellationToken,
                                                runtime.TaskFactory.CreationOptions, runtime.TaskFactory.Scheduler));
        }
Beispiel #4
0
        /// <summary>
        /// Creates and starts a generic task.
        /// </summary>
        public static SystemTasks.Task <TResult> StartNew <TResult>(SystemTaskFactory factory,
                                                                    Func <object, TResult> function, object state, SystemCancellationToken cancellationToken)
        {
            var runtime = CoyoteRuntime.Current;

            if (runtime.SchedulingPolicy is SchedulingPolicy.None)
            {
                return(factory.StartNew(function, state, cancellationToken));
            }

            return(runtime.TaskFactory.StartNew(function, state, cancellationToken,
                                                runtime.TaskFactory.CreationOptions, runtime.TaskFactory.Scheduler));
        }
Beispiel #5
0
        /// <summary>
        /// Creates and starts a task.
        /// </summary>
        public static SystemTask StartNew(SystemTaskFactory factory, Action action, SystemCancellationToken cancellationToken,
                                          SystemTaskCreationOptions creationOptions, SystemTaskScheduler scheduler)
        {
            var runtime = CoyoteRuntime.Current;

            if (runtime.SchedulingPolicy is SchedulingPolicy.None ||
                scheduler.GetType() != SystemTaskScheduler.Default.GetType())
            {
                return(factory.StartNew(action, cancellationToken, creationOptions, scheduler));
            }

            return(runtime.TaskFactory.StartNew(action, cancellationToken,
                                                runtime.TaskFactory.CreationOptions | creationOptions,
                                                runtime.TaskFactory.Scheduler));
        }
Beispiel #6
0
        /// <summary>
        /// Creates and starts a task.
        /// </summary>
        public static SystemTasks.Task <TResult> StartNew <TResult>(SystemTaskFactory factory,
                                                                    Func <object, TResult> function, object state, SystemCancellationToken cancellationToken,
                                                                    SystemTaskCreationOptions creationOptions, SystemTaskScheduler scheduler)
        {
            var runtime = CoyoteRuntime.Current;

            if (runtime.SchedulingPolicy is SchedulingPolicy.None ||
                scheduler.GetType() != SystemTaskScheduler.Default.GetType())
            {
                return(factory.StartNew(function, state, cancellationToken, creationOptions, scheduler));
            }

            return(runtime.TaskFactory.StartNew(function, state, cancellationToken,
                                                runtime.TaskFactory.CreationOptions | creationOptions,
                                                runtime.TaskFactory.Scheduler));
        }
Beispiel #7
0
        /// <inheritdoc />
        public void Start(Action action)
        {
            _cancellationTokenSource = new CancellationTokenSource();

            _task = _taskFactory.StartNew(action, _cancellationTokenSource.Token);
        }
Beispiel #8
0
 public static Task <T> StartNewDexterTask <T>(this TaskFactory factory, Func <T> action, TaskCreationOptions options = TaskCreationOptions.None)
 {
     return(factory.StartNew(CreateNewFunc(action), options));
 }
Beispiel #9
0
 public static Task StartNewDexterTask(this TaskFactory factory, Action action, TaskCreationOptions options = TaskCreationOptions.None)
 {
     return(factory.StartNew(CreateNewAction(action), options));
 }
Beispiel #10
0
        /// <summary>Asynchronously iterates through an enumerable of tasks.</summary>
        /// <param name="factory">The target factory.</param>
        /// <param name="source">The enumerable containing the tasks to be iterated through.</param>
        /// <param name="state">The asynchronous state for the returned Task.</param>
        /// <param name="cancellationToken">The cancellation token used to cancel the iteration.</param>
        /// <param name="creationOptions">Options that control the task's behavior.</param>
        /// <param name="scheduler">The scheduler to which tasks will be scheduled.</param>
        /// <returns>A Task that represents the complete asynchronous operation.</returns>
        public static Task Iterate(
            this TaskFactory factory,
            IEnumerable <object> source, object state,
            CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
        {
            // Validate/update parameters
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (source == null)
            {
                throw new ArgumentNullException("asyncIterator");
            }
            if (scheduler == null)
            {
                throw new ArgumentNullException("scheduler");
            }

            // Get an enumerator from the enumerable
            var enumerator = source.GetEnumerator();

            if (enumerator == null)
            {
                throw new InvalidOperationException("Invalid enumerable - GetEnumerator returned null");
            }

            // Create the task to be returned to the caller.  And ensure
            // that when everything is done, the enumerator is cleaned up.
            var trs = new TaskCompletionSource <object>(state, creationOptions);

            trs.Task.ContinueWith(_ => enumerator.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);

            // This will be called every time more work can be done.
            Action <Task> recursiveBody = null;

            recursiveBody = antecedent =>
            {
                try
                {
                    // If we should continue iterating and there's more to iterate
                    // over, create a continuation to continue processing.  We only
                    // want to continue processing once the current Task (as yielded
                    // from the enumerator) is complete.
                    if (enumerator.MoveNext())
                    {
                        var nextItem = enumerator.Current;

                        // If we got a Task, continue from it to continue iterating
                        if (nextItem is Task)
                        {
                            var nextTask = (Task)nextItem;
                            /**/ nextTask.IgnoreExceptions(); // TODO: Is this a good idea?
                            nextTask.ContinueWith(recursiveBody).IgnoreExceptions();
                        }
                        // If we got a scheduler, continue iterating under the new scheduler,
                        // enabling hopping between contexts.
                        else if (nextItem is TaskScheduler)
                        {
                            Task.Factory.StartNew(() => recursiveBody(null), CancellationToken.None, TaskCreationOptions.None, (TaskScheduler)nextItem).IgnoreExceptions();
                        }
                        // Anything else is invalid
                        else
                        {
                            trs.TrySetException(new InvalidOperationException("Task or TaskScheduler object expected in Iterate"));
                        }
                    }

                    // Otherwise, we're done!
                    else
                    {
                        trs.TrySetResult(null);
                    }
                }
                // If MoveNext throws an exception, propagate that to the user,
                // either as cancellation or as a fault
                catch (Exception exc)
                {
                    var oce = exc as OperationCanceledException;
                    if (oce != null && oce.CancellationToken == cancellationToken)
                    {
                        trs.TrySetCanceled();
                    }
                    else
                    {
                        trs.TrySetException(exc);
                    }
                }
            };

            // Get things started by launching the first task
            factory.StartNew(() => recursiveBody(null), CancellationToken.None, TaskCreationOptions.None, scheduler).IgnoreExceptions();

            // Return the representative task to the user
            return(trs.Task);
        }
 /// <summary>
 /// Executes an async Task method which has a void return value synchronously
 /// USAGE: AsyncUtil.RunSync(() => AsyncMethod());
 /// </summary>
 /// <param name="task">Task method to execute</param>
 public static void RunSync(Func <Task> task)
 => _taskFactory
 .StartNew(task)
 .Unwrap()
 .GetAwaiter()
 .GetResult();