1 //--------------------------------------------------------------------------
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // File: TaskFactoryExtensions_Common.cs
7 //--------------------------------------------------------------------------
9 namespace System.Threading.Tasks
11 /// <summary>Extensions for TaskFactory.</summary>
12 public static partial class TaskFactoryExtensions
14 /// <summary>Creates a generic TaskFactory from a non-generic one.</summary>
15 /// <typeparam name="TResult">Specifies the type of Task results for the Tasks created by the new TaskFactory.</typeparam>
16 /// <param name="factory">The TaskFactory to serve as a template.</param>
17 /// <returns>The created TaskFactory.</returns>
18 public static TaskFactory<TResult> ToGeneric<TResult>(this TaskFactory factory)
20 return new TaskFactory<TResult>(
21 factory.CancellationToken, factory.CreationOptions, factory.ContinuationOptions, factory.Scheduler);
24 /// <summary>Creates a generic TaskFactory from a non-generic one.</summary>
25 /// <typeparam name="TResult">Specifies the type of Task results for the Tasks created by the new TaskFactory.</typeparam>
26 /// <param name="factory">The TaskFactory to serve as a template.</param>
27 /// <returns>The created TaskFactory.</returns>
28 public static TaskFactory ToNonGeneric<TResult>(this TaskFactory<TResult> factory)
30 return new TaskFactory(
31 factory.CancellationToken, factory.CreationOptions, factory.ContinuationOptions, factory.Scheduler);
34 /// <summary>Gets the TaskScheduler instance that should be used to schedule tasks.</summary>
35 public static TaskScheduler GetTargetScheduler(this TaskFactory factory)
37 if (factory == null) throw new ArgumentNullException("factory");
38 return factory.Scheduler ?? TaskScheduler.Current;
41 /// <summary>Gets the TaskScheduler instance that should be used to schedule tasks.</summary>
42 public static TaskScheduler GetTargetScheduler<TResult>(this TaskFactory<TResult> factory)
44 if (factory == null) throw new ArgumentNullException("factory");
45 return factory.Scheduler != null ? factory.Scheduler : TaskScheduler.Current;
48 /// <summary>Converts TaskCreationOptions into TaskContinuationOptions.</summary>
49 /// <param name="creationOptions"></param>
50 /// <returns></returns>
51 private static TaskContinuationOptions ContinuationOptionsFromCreationOptions(TaskCreationOptions creationOptions)
53 return (TaskContinuationOptions)
54 ((creationOptions & TaskCreationOptions.AttachedToParent) |
55 (creationOptions & TaskCreationOptions.PreferFairness) |
56 (creationOptions & TaskCreationOptions.LongRunning));