class BrokenArgumentValidation
{
static void Main()//异步方法中断的参数验证
{
MainAsync().Wait();
}
static async Task MainAsync()
{
Task<int> task = ComputeLengthAsync(null);//故意传入错误的参数
Console.WriteLine("Fetched the task");
int length = await task;//等待结果
Console.WriteLine("Length: {0}", length);
}
static async Task<int> ComputeLengthAsync(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");//立即抛出异常
}
await Task.Delay(500); // 模拟真实的异步工作
return text.Length;
}
}
与迭代器类似,参数验证会有些麻烦。假设我们在验证完参数不含有空值后,想在异步
方法里做一些处理。像在同步代码那样验证参数,那么在等待任务之前,调用者不会得到
任何错误提示。
在失败之前会先输出Fetched the task。实际上,输出这条结果之前&