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(); }
/// <summary> /// The default task cancellation token for this task factory. /// </summary> public static SystemCancellationToken get_CancellationToken(SystemTaskFactory factory) { var runtime = CoyoteRuntime.Current; if (runtime.SchedulingPolicy is SchedulingPolicy.None) { return(factory.CancellationToken); } return(runtime.TaskFactory.CancellationToken); }
/// <summary> /// The default task scheduler for this task factory. /// </summary> public static SystemTaskScheduler get_Scheduler(SystemTaskFactory factory) { var runtime = CoyoteRuntime.Current; if (runtime.SchedulingPolicy is SchedulingPolicy.None) { return(factory.Scheduler); } return(runtime.TaskFactory.Scheduler); }
/// <summary> /// The default task creation options for this task factory. /// </summary> public static SystemTaskCreationOptions get_CreationOptions(SystemTaskFactory factory) { var runtime = CoyoteRuntime.Current; if (runtime.SchedulingPolicy is SchedulingPolicy.None) { return(factory.CreationOptions); } return(runtime.TaskFactory.CreationOptions); }
/// <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)); }
/// <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)); }
/// <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)); }
/// <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)); }
static void Main(string[] args) { // connect to app service and wait until the connection gets closed taskFactory = new TaskFactory(); LogMessage("Win32Proc: Main"); appServiceExit = new AutoResetEvent(false); LogMessage("Win32Proc: Calling ConnectToAppService"); bool result = RunSync(() => ConnectToAppService()); if (result == true) { LogMessage("Win32Proc: Calling SendIntializeCommandToAppService"); result = RunSync(() => SendIntializeCommandToAppService()); if (result == true) { LogMessage("Win32Proc: Win32Proc Connected to AppService"); } } appServiceExit.WaitOne(); }
/// <summary> /// Creates and starts a task. /// </summary> public static SystemTask StartNew(SystemTaskFactory factory, Action <object> action, object state) => StartNew(factory, action, state, SystemCancellationToken.None);
/// <summary>Creates a continuation task using the specified TaskFactory.</summary> /// <param name="task">The antecedent Task.</param> /// <param name="continuationAction">The continuation action.</param> /// <param name="factory">The TaskFactory.</param> /// <returns>A continuation task.</returns> public static Task ContinueWith <TResult>( this Task <TResult> task, Action <Task <TResult> > continuationAction, TaskFactory <TResult> factory) { return(task.ContinueWith(continuationAction, factory.CancellationToken, factory.ContinuationOptions, factory.Scheduler)); }
/// <summary> /// Creates and starts a task. /// </summary> public static SystemTasks.Task <TResult> StartNew <TResult>(SystemTaskFactory factory, Func <object, TResult> function, object state, SystemTaskCreationOptions creationOptions) => StartNew(factory, function, state, SystemCancellationToken.None, creationOptions, SystemTaskScheduler.Default);
/// <summary> /// Creates and starts a generic task. /// </summary> public static SystemTasks.Task <TResult> StartNew <TResult>(SystemTaskFactory factory, Func <object, TResult> function, object state) => StartNew(factory, function, state, SystemCancellationToken.None);
/// <summary> /// Creates and starts a task. /// </summary> public static SystemTask StartNew(SystemTaskFactory factory, Action <object> action, object state, SystemTaskCreationOptions creationOptions) => StartNew(factory, action, state, SystemCancellationToken.None, creationOptions, SystemTaskScheduler.Default);
/// <summary> /// Creates and starts a task. /// </summary> public static SystemTasks.Task <TResult> StartNew <TResult>(SystemTaskFactory factory, Func <TResult> function, SystemCancellationToken cancellationToken) => StartNew(factory, function, cancellationToken, SystemTaskCreationOptions.None, SystemTaskScheduler.Default);
/// <summary> /// Creates a continuation Task that will complete upon /// the completion of any one of a set of provided Tasks. /// </summary> /// <param name="factory">The TaskFactory to use to create the continuation task.</param> /// <param name="tasks">The array of tasks from which to continue.</param> /// <returns>A task that, when completed, will return the completed task.</returns> public static Task <Task <TAntecedentResult> > WhenAny <TAntecedentResult>( this TaskFactory factory, params Task <TAntecedentResult>[] tasks) { return(factory.ContinueWhenAny(tasks, completedTask => completedTask)); }
#pragma warning restore CA1707 // Remove the underscores from member name #pragma warning restore SA1300 // Element should begin with an uppercase letter #pragma warning restore IDE1006 // Naming Styles /// <summary> /// Creates and starts a task. /// </summary> public static SystemTask StartNew(SystemTaskFactory factory, Action action) => StartNew(factory, action, SystemCancellationToken.None);
static Parallel() { Factory = new TaskFactory(); }
/// <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); }
public static void RunTest(int shardCount, int itemsCount, int customerItemsCount) { int totalSuccess = 0; var tasks = new List <Task>(); var factory = new System.Threading.Tasks.TaskFactory(); //using (GetTransaction()) //{ Console.WriteLine($"Running test with {shardCount} shards and {itemsCount} items and {customerItemsCount} customer items"); ShardConfiguration shardConfiguration = new ShardConfiguration(shardCount); IShardKeyAlgorithm shardKeyAlgorithm = new EvenlyDistributedShardKeyAlgorithm(shardConfiguration); using (SqlDb db = new SqlDb(shardConfiguration, shardKeyAlgorithm)) { try { //db.ClearAll(); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < itemsCount; i++) { try { db.AddCustomer(new Common.SampleCustomerInformation() { CustomerId = i, Title = $"Customer {i}", Address = "Address one + two", Birthdate = DateTime.Now, Job = "Jobs of the future is related to data" }); Interlocked.Increment(ref totalSuccess); } catch (Exception ex) { } } sw.Stop(); var avg = sw.ElapsedMilliseconds / itemsCount; Console.WriteLine($"ShardCount: {shardCount}, Insert Count: {itemsCount}, Avg: {avg}, Total Success: {totalSuccess}"); sw.Reset(); sw.Start(); var list = Enumerable.Range(0, itemsCount).ToList(); Parallel.ForEach(list, (customerId) => { //foreach (var customerId in list) //{ for (int i = 0; i < customerItemsCount; i++) { try { db.AddOrder(new Common.SampleOrderInformation() { CustomerId = customerId, Count = customerId + i + 10, Price = (customerId + i + 3453) * 10, Description = "some order detail", OrderEntryDate = DateTime.Now }); } catch (Exception ex) { } } }); //} sw.Stop(); avg = sw.ElapsedMilliseconds / itemsCount; Console.WriteLine($"ShardCount: {shardCount}, Insert Count: {itemsCount * customerItemsCount}, Avg: {avg}, Total: {sw.Elapsed.TotalSeconds:0.0}"); } finally { db.ClearAll(); } } }
public static Task StartNewDexterTask(this TaskFactory factory, Action action, TaskCreationOptions options = TaskCreationOptions.None) { return(factory.StartNew(CreateNewAction(action), options)); }
/// <summary>Creates a continuation task using the specified TaskFactory.</summary> /// <param name="task">The antecedent Task.</param> /// <param name="continuationFunction">The continuation function.</param> /// <param name="factory">The TaskFactory.</param> /// <returns>A continuation task.</returns> public static Task <TResult> ContinueWith <TResult>( this Task task, Func <Task, TResult> continuationFunction, TaskFactory factory) => task.ContinueWith(continuationFunction, factory.CancellationToken, factory.ContinuationOptions, factory.Scheduler);
/// <summary>Creates a continuation task using the specified TaskFactory.</summary> /// <param name="task">The antecedent Task.</param> /// <param name="continuationAction">The continuation action.</param> /// <param name="factory">The TaskFactory.</param> /// <returns>A continuation task.</returns> public static Task ContinueWith( this Task task, Action <Task> continuationAction, TaskFactory factory) => task.ContinueWith(continuationAction, factory.CancellationToken, factory.ContinuationOptions, factory.Scheduler);
public static Task <T> StartNewDexterTask <T>(this TaskFactory factory, Func <T> action, TaskCreationOptions options = TaskCreationOptions.None) { return(factory.StartNew(CreateNewFunc(action), options)); }
#pragma warning restore CA1707 // Remove the underscores from member name #pragma warning restore SA1300 // Element should begin with an uppercase letter #pragma warning restore IDE1006 // Naming Styles /// <summary> /// Creates and starts a task. /// </summary> public static SystemTask StartNew(SystemTaskFactory factory, Action action) => StartNew(factory, action, SystemCancellationToken.None, SystemTaskCreationOptions.None, SystemTaskScheduler.Default);
/// <summary>Creates a continuation task using the specified TaskFactory.</summary> /// <param name="task">The antecedent Task.</param> /// <param name="continuationFunction">The continuation function.</param> /// <param name="factory">The TaskFactory.</param> /// <returns>A continuation task.</returns> public static Task <TNewResult> ContinueWith <TResult, TNewResult>( this Task <TResult> task, Func <Task <TResult>, TNewResult> continuationFunction, TaskFactory <TResult> factory) { return(task.ContinueWith(continuationFunction, factory.CancellationToken, factory.ContinuationOptions, factory.Scheduler)); }
/// <inheritdoc /> public Task(System.Threading.Tasks.TaskFactory taskFactory) { _taskFactory = taskFactory; }
/// <summary> /// Creates a continuation Task that will compplete upon /// the completion of a set of provided Tasks. /// </summary> /// <param name="factory">The TaskFactory to use to create the continuation task.</param> /// <param name="tasks">The array of tasks from which to continue.</param> /// <returns>A task that, when completed, will return the array of completed tasks.</returns> public static Task <Task <TAntecedentResult>[]> WhenAll <TAntecedentResult>( this TaskFactory factory, params Task <TAntecedentResult>[] tasks) { return(factory.ContinueWhenAll(tasks, completedTasks => completedTasks) as Task <Task <TAntecedentResult>[]>); }
/// <summary> /// Creates a continuation Task that will complete upon /// the completion of any one of a set of provided Tasks. /// </summary> /// <param name="factory">The TaskFactory to use to create the continuation task.</param> /// <param name="tasks">The array of tasks from which to continue.</param> /// <returns>A task that, when completed, will return the completed task.</returns> public static Task <Task> WhenAny( this TaskFactory factory, params Task[] tasks) { return(factory.ContinueWhenAny(tasks, completedTask => completedTask)); }
/// <summary> /// Gets the TaskScheduler instance that should be used to schedule tasks. /// </summary> /// <typeparam name="TResult">Specifies the type of Task result for the Task created by the new TaskFactory.</typeparam> /// <param name="factory">The TaskFactory to serve as a template.</param> /// <returns>The created TaskScheduler.</returns> public static TaskScheduler GetTargetScheduler <TResult>(this TaskFactory <TResult> factory) { Contract.Requires(factory != null); return(factory.Scheduler != null ? factory.Scheduler : TaskScheduler.Current); }