相关疑难解决方法(0)

应该返回Task的方法抛出异常吗?

返回的方法Task有两个报告错误的选项:

  1. 立刻抛出异常
  2. 返回将以异常结束的任务

调用者是否应该期望两种类型的错误报告,或者是否存在将任务行为限制为第二个选项的某些标准/协议?

例:

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解决方案?

.net c# asynchronous .net-4.0 task-parallel-library

13
推荐指数
1
解决办法
3690
查看次数

标签 统计

.net ×1

.net-4.0 ×1

asynchronous ×1

c# ×1

task-parallel-library ×1