不,
async
/
await
关键字与并发有很大关系。
async
/
await
基本上将你的方法代码包装成一个任务和继续操作。要查看编译器使用任务并行库生成的确切翻译,请反汇编一些代码片段。这种
async
/
await
用法的翻译与下面的示例“类似”(但不完全相同!)。
async Task<int> TaskOfTResult_MethodAsync()
{
int hours;
return hours;
}
Task<int> returnedTaskTResult = TaskOfTResult_MethodAsync();
int intResult = await returnedTaskTResult;
int intResult = await TaskOfTResult_MethodAsync();
这大致转换为:
private int Result()
{
int hours;
return hours;
}
在方法外等待返回结果,例如:
int? hours = null;
Task<int> task = null;
task = Task.Factory.StartNew<int>(() => Result());
task.ContnueWith(cont =>
{
// Some task completion checking...
hours = task.Result;
}, CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Current);
或者,你可以将TPL代码放入
Result
方法中。
private int ResultAsync()
{
int? hours = null;
Task<int> task = null;
task = Task.Factory.StartNew<int>(() =>
{
int hours;
// . . .
// Return statement specifies an integer result.
return hours;
}, CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Current);
try
{
return task.Result;
}
catch (AggregateException aggEx)
{
// Some handler method for the agg exception.
aggEx.Handle(HandleException);
}
}
SynchronizationContext
不能保证 async
/await
代码的继续执行将在同一线程上执行。但是,您可以使用 TPL 代码通过 SynchronisationContex
关键字来设置上下文。