async/lambdas StartNew :
var task = Task.Factory.StartNew(async () => { });
task.Wait();
task.Result.Wait();
Unwrap StartNew .
var task = Task.Factory.StartNew(async () => { })
.Unwrap();
task.Wait();
, Task.Factory.StartNew ContinueWith , , .
, Task.Factory.StartNew , , ( ) Task.Run , Task.Factory.StartNew, TaskCreationOptions TaskScheduler.
, Task.Factory. , StartNew , .
, , ContinueWith , , ( ) async/await , ContinueWith t TaskContinuationOptions TaskScheduler.
, # 5 await, catch finally, ContinueWith.
# 6:
try
{
return await something;
}
catch (SpecificException ex)
{
await somethingElse;
// throw;
}
finally
{
await cleanup;
}
# 6:
return await something
.ContinueWith(async somethingTask =>
{
var ex = somethingTask.Exception.InnerException as SpecificException;
if (ex != null)
{
await somethingElse;
}
},
CancellationToken.None,
TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.NotOnRanToCompletion,
TaskScheduler.Default)
.Unwrap()
.ContinueWith(async catchTask =>
{
await cleanup;
await catchTask;
},
CancellationToken.None,
TaskContinuationOptions.DenyChildAttach,
TaskScheduler.Default)
.Unwrap();
, , TaskFactory , , TaskFactory, (I factory):
public static Task ContinueWhen(this TaskFactory taskFactory, Task task, Action<Task> continuationAction)
{
return task.ContinueWith(continuationAction, taskFactory.CancellationToken, taskFactory.ContinuationOptions, taskFactory.Scheduler);
}
public static Task<TResult> ContinueWhen<TResult>(this TaskFactory taskFactory, Task task, Func<Task, TResult> continuationFunction)
{
return task.ContinueWith(continuationFunction, taskFactory.CancellationToken, taskFactory.ContinuationOptions, taskFactory.Scheduler);
}
:
var task = taskFactory.ContinueWhen(existsingTask, t => Continue(a, b, c));
var asyncTask = taskFactory.ContinueWhen(existingTask, async t => await ContinueAsync(a, b, c))
.Unwrap();
Task.Run, , , , . , ContinueWhenAsync, Unwrap await s.
-, , , (, MemoryStream ). , .
, Unwrap await s, , . , async/await, , , .
. , , async/await - , , , async, (ASP.NET, WCF, NServiceBus 6+ ..), - . Task.Yield. - , : .
If the asynchronous operation depends on the synchronization context, you can still use async/ awaitif you are in this context (in this case, think twice or more before using .ConfigureAwait(false)), otherwise start a new task using the task scheduler from the corresponding synchronization context.