如何在Todictionary C#中使用TryCatch语句?
我有一个异步电话的字典。问题有时是这些异步电话会引发例外,但我不确定如何处理它们。 getUserlicenseTypes返回列表,因此,如果我确实得到异常,我仍然想返回一个空列表。
var tasks = allCompanyUsers.ToDictionary(
u => u.Id,
u => _subscriptionService.GetUserSubscription(companyId, u.Id));
await Task.WhenAll(tasks.Values);
var licenseListByUserId = tasks.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Result);
下面的代码不起作用,但我想做类似的
var tasks = allCompanyUsers.ToDictionary(
u => u.Id,
u => {
try{
return _subscriptionService.GetUserSubscription(companyId, u.Id);
}catch{
return new List<string>();
}
});
await Task.WhenAll(tasks.Values);
var licenseListByUserId = tasks.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Result);
注意事项:我得到了反馈,我应该避免在一起例外,但是目前很难考虑到getUserSubscription函数已经在许多位置都使用了我们的应用程序使用的典型惯例是trycatch语句来处理这些抛出的错误。
I have a dictionary of asyncronous call . The problem is sometimes these asyncronous call will throw an exception but I am not entirely sure how to handle them . The GetUserLicenseTypes returns a list so if I do get an exception I still want to return an empty list.
var tasks = allCompanyUsers.ToDictionary(
u => u.Id,
u => _subscriptionService.GetUserSubscription(companyId, u.Id));
await Task.WhenAll(tasks.Values);
var licenseListByUserId = tasks.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Result);
The code below doesn't work but I wanted to do something like this
var tasks = allCompanyUsers.ToDictionary(
u => u.Id,
u => {
try{
return _subscriptionService.GetUserSubscription(companyId, u.Id);
}catch{
return new List<string>();
}
});
await Task.WhenAll(tasks.Values);
var licenseListByUserId = tasks.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Result);
Note : I have gotten feedback that I should just avoid exception all together but at the moment it is hard to do considering that the GetUserSubscription function is already used in many location so the typical convention our application use is a trycatch statement to handle these thrown error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种方法:
因为
task
正在等待从getUserSubscription
返回,所以它将解开并丢弃任何异常
,这意味着中的值捕获
将返回。Here's one way:
Because the
Task
returned fromGetUserSubscription
is awaited, it will unwrap and throw anyException
, meaning the value in thecatch
block will be returned.它看起来像
task&lt; string&gt;&gt;
的字典值类型,但是在您的捕获块中,您返回list&lt; string&gt;
。如果您返回任务,它应该有效:It looks as the type of the values of your dictionary is
Task<List<string>>
, but in your catch block you return aList<string>
. If you return a task, it should work: