Gle*_*cia 8 c# parallel-processing asynchronous task task-parallel-library
例如,这段代码之间的区别
public Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h")
{
var result = _conf.BasePath
.AppendPathSegment("news-sentiment-indexes")
.SetQueryParams(new
{
from = from.ToString("s"),
to = to.ToString("s"),
grouping
});
return result
.GetStringAsync()
.ContinueWith(Desereialize<IList<NewsSentimentIndexes>>);
}
Run Code Online (Sandbox Code Playgroud)
然后
public async Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h")
{
var result = _conf.BasePath
.AppendPathSegment("news-sentiment-indexes")
.SetQueryParams(new
{
from = from.ToString("s"),
to = to.ToString("s"),
grouping
});
var newsStr = await result.GetStringAsync();
return JsonConvert.DeserializeObject<NewsSentimentIndexes>(newsStr);
}
Run Code Online (Sandbox Code Playgroud)
哪一个正确或更快?只是调用这个方法需要等待或只是一个任务?
在async一个更好.你应该总是喜欢用await而不是ContinueWith.我在博客上详细介绍了为什么ContinueWith不好.
这两种实现之间的语义差异是由于两个不同:是否async使用,以及是否ContinueWith使用.
删除async更改异常语义.当async使用时,任何异常(由编译器生成的状态机)抓住和放置在返回的任务.没有async,直接(同步)引发异常.所以,如果BasePath,AppendPathSegment,SetQueryParams,或GetStringAsync抛出(或返回null或类似的东西),则该异常将被同步而不是异步上调,这可能是混乱的来电.
使用ContinueWith更改执行语义.在这种情况下,Deserialize将安排在TaskScheduler.Current.这种对电流的依赖TaskScheduler是最棘手的部分之一ContinueWith.
| 归档时间: |
|
| 查看次数: |
155 次 |
| 最近记录: |