返回的方法Task有两个报告错误的选项:
调用者是否应该期望两种类型的错误报告,或者是否存在将任务行为限制为第二个选项的某些标准/协议?
例:
class PageChecker {
Task CheckWebPage(string url) {
if(url == null) // Argument check
throw Exception("Bad URL");
if(!HostPinger.IsHostOnline(url)) // Some other synchronous check
throw Exception("Host is down");
return Task.Factory.StartNew(()=> {
// Asynchronous check
if(PageDownloader.GetPageContent(url).Contains("error"))
throw Exception("Error on the page");
});
}
}
Run Code Online (Sandbox Code Playgroud)
处理这两种类型看起来很丑陋:
try {
var task = pageChecker.CheckWebPage(url);
task.ContinueWith(t =>
{
if(t.Exception!=null)
ReportBadPage(url);
});
}
catch(Exception ex) {
ReportBadPage(url);
}
Run Code Online (Sandbox Code Playgroud)
使用async/await可能有所帮助,但有没有异步支持的纯.NET 4解决方案?