Unfortunately, is not exactly correct that Task.Run
is same as Task.Factory.StartNew
.
In this answer , it is given the closest thing to Task.Run
in 4.0 which 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);
}
that can be used like:
Task
.Factory
.StartNewOnDefaultScheduler(() =>
result);
But Task.Run
is a nice wrapper over Task.Factory.StartNew
introduced in .NET 4.5
.
But for your situation, when you need it for multithreading
operations, just use it.
But don't forget.
You should prefer Task.Run
over Task.Factory.StartNew
if you use async
code.
In this article , Stephen Curry gives two reason that StartNew
method is dangerous:
- Does not understand async delegates.
- Confusing default scheduler.