深⼊理解c#第⼗五章使⽤异步匿名函数进⾏参数验证异步匿名
函数
class FixedArgumentValidationAsyncLambda
{
static void Main()//使⽤异步匿名函数进⾏参数验证
{
MainAsync().Wait();
}
static async Task MainAsync()
{
writeline函数Task<int> task = ComputeLengthAsync(null);
/
/ We never get this far, as the exception is thrown eagerly.
Console.WriteLine("Fetched the task");
int length = await task;
Console.WriteLine("Length: {0}", length);
}
static Task<int> ComputeLengthAsync(string text)
//text null
{
if (text == null)//执⾏这句完全异步验证
{
throw new ArgumentNullException("text");//回主函数
}
Func<Task<int>> func = async () =>  //创建⼀个异步函数
{
await Task.Delay(500); // 模拟真正异步⼯作
return text.Length;
};
return func(); //调⽤匿名函数
}
}
你会发现这并不是⼀个异步⽅法。如果是的话,异步会被包装到任务⾥,⽽不是⽴即抛出。
但我们还是想返回⼀个任务,因为在验证之后,将⼯作包装到⼀个异步匿名函数中,调⽤委托
并返回结果。
尽管看上去有点丑,但⽐分割成两个⽅法要清晰多了。不过性能会有点损失,额外的包装
会产⽣额外的代价。在⼤多数情况下没有问题,但如果需要注意性能的程序,则应在真实场景
检测成本,然后决定采取⽅法。
输出
Exception: System.Reflection.TargetInvocationException: 调⽤的⽬标发⽣了异常。 ---> System.AggregateException: 发⽣⼀个 或多个错误。 ---> System.ArgumentNullException: 值不能为 null。
参数名: text
在 Chapter15.FixedArgumentValidationAsyncLambda.ComputeLengthAsync(String text) 位置FixedArgumentValidationAsyncLambda.cs:⾏号 28 ⽂件路径
在 Chapter15.FixedArgumentValidationAsyncLambda.<MainAsync>d__0.MoveNext() 位置FixedArgumentValidationAsyncLambda.cs:⾏号 17 ⽂件路径
--- 内部异常堆栈跟踪的结尾 ---
在 System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
在 System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
在 System.Threading.Tasks.Task.Wait()
在 Chapter15.FixedArgumentValidationAsyncLambda.Main() 位置 c:\Users\Adminstrator\Desktop\深⼊理解C# 第三版 源代码 - 副本\C# in Depth\OtherChapters\Chapter15\FixedArgumentValidationAsyncLambda.cs:⾏号 12
--- 内部异常堆栈跟踪的结尾 ---
在 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
在 System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
在 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
在 MiscUtil.ApplicationChooser.Run(Type type, String[] args)