在递归方法中使用 Yield return 的 Try-Catch
Try-Catch with Yield return in a Recursive Method
我需要在递归方法中实现 try catch,但我不知道该怎么做。这是代码:
private IEnumerable <FileItem> FilesToDownload(FileItem file)
{
logger = LogManager.GetLogger(GetType());
using (var wb = new WebDavSession(webDavUrl, new NetworkCredential(user, psw)))
using (Task<IList<WebDavSessionItem>> task = wb.ListAsync(file.Path))
{
task.Wait();
foreach (var item in task.Result)
{
FileItem retFile = item.ToFileItem();
logger.Info("Going Into " + retFile.Path);
if (item.IsFolder == true)
{
foreach (var inner in FilesToDownload(retFile))
{
yield return inner;
}
}
else
{
yield return retFile;
}
}
}
}
这个方法帮助我找到嵌套文件夹中的文件(在云中),所以递归是必要的。
你有什么建议?
你不能做的是有一个try
/catch
块周围一个yield return
声明 - 违反了 CS1626.
但是:您仍然可以使用 try
/catch
- 您只需要在布局上发挥创意。例如:
foreach (var item in task.Result)
{
IEnumerable<FileItem> subItems = null;
FileItem subItem = null;
try
{
FileItem retFile = item.ToFileItem();
logger.Info("Going Into " + retFile.Path);
if (item.IsFolder == true)
{
subItems = FilesToDownload(retFile);
}
else
{
subItem = retFile;
}
}
catch { /* your code here */ }
if (subItem != null) yield return subItem;
if (subItems != null)
{
foreach (var x in subItems) yield return x;
}
}
其他想法:
- a
Stack<T>
或 Queue<T>
可能是比深度递归更合适的方法
task.Wait()
不好,可能会使您的代码死锁;不幸的是,目前 "async enumerables" 没有好的模式
我需要在递归方法中实现 try catch,但我不知道该怎么做。这是代码:
private IEnumerable <FileItem> FilesToDownload(FileItem file)
{
logger = LogManager.GetLogger(GetType());
using (var wb = new WebDavSession(webDavUrl, new NetworkCredential(user, psw)))
using (Task<IList<WebDavSessionItem>> task = wb.ListAsync(file.Path))
{
task.Wait();
foreach (var item in task.Result)
{
FileItem retFile = item.ToFileItem();
logger.Info("Going Into " + retFile.Path);
if (item.IsFolder == true)
{
foreach (var inner in FilesToDownload(retFile))
{
yield return inner;
}
}
else
{
yield return retFile;
}
}
}
}
这个方法帮助我找到嵌套文件夹中的文件(在云中),所以递归是必要的。
你有什么建议?
你不能做的是有一个try
/catch
块周围一个yield return
声明 - 违反了 CS1626.
但是:您仍然可以使用 try
/catch
- 您只需要在布局上发挥创意。例如:
foreach (var item in task.Result)
{
IEnumerable<FileItem> subItems = null;
FileItem subItem = null;
try
{
FileItem retFile = item.ToFileItem();
logger.Info("Going Into " + retFile.Path);
if (item.IsFolder == true)
{
subItems = FilesToDownload(retFile);
}
else
{
subItem = retFile;
}
}
catch { /* your code here */ }
if (subItem != null) yield return subItem;
if (subItems != null)
{
foreach (var x in subItems) yield return x;
}
}
其他想法:
- a
Stack<T>
或Queue<T>
可能是比深度递归更合适的方法 task.Wait()
不好,可能会使您的代码死锁;不幸的是,目前 "async enumerables" 没有好的模式