The highest voted answer , unfortunately, is not entirely correct :
Unfortunately, the only overloads for StartNew that accept TaskScheduler also require that you specify CancellationToken and TaskCreationOptions. This means that in order to use Task.Factory.StartNew to work reliably with the predicted queue in the thread pool, you need to use the following overload:
Task.Factory.StartNew (A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
So, the closest thing to Task.Run in 4.0 is something like:
/// <summary> /// Starts the new <see cref="Task"/> from <paramref name="function"/> on the Default(usually ThreadPool) task scheduler (not on the TaskScheduler.Current). /// It is a 4.0 method nearly analogous to 4.5 Task.Run. /// </summary> /// <typeparam name="T">The type of the return value.</typeparam> /// <param name="factory">The factory to start from.</param> /// <param name="function">The function to execute.</param> /// <returns>The task representing the execution of the <paramref name="function"/>.</returns> public static Task<T> StartNewOnDefaultScheduler<T>(this TaskFactory factory, Func<T> function) { Contract.Requires(factory != null); Contract.Requires(function != null); return factory .StartNew( function, cancellationToken: CancellationToken.None, creationOptions: TaskCreationOptions.None, scheduler: TaskScheduler.Default); }
which can be used as:
Task .Factory .StartNewOnDefaultScheduler(() => result);
Eugene Podskal Jan 30 '17 at 16:01 2017-01-30 16:01
source share