【问题标题】:continue foreach loop from dispatcher从调度程序继续 foreach 循环
【发布时间】:2019-02-11 07:40:03
【问题描述】:

我有一个 foreach 循环,我在里面使用了调度程序,里面还有另一个 foreach。检查结果后我想先继续foreach。

bool isNude = false;
var SearchTask = Task.Run(async () =>
{
    foreach (var file in await GetFileListAsync(GlobalData.Config.DataPath))
    {
        isNude = false;
        if (!ct.IsCancellationRequested)
        {
            await Dispatcher.InvokeAsync(() =>
            {
                if (ButtonNude.IsChecked == true)
                {
                    foreach (var itemx in nudeData)
                    {
                        if (itemx.Equals(Path.GetFileNameWithoutExtension(file.FullName)))
                        {
                            isNude = true;
                            break;
                        }
                    }
                }
                if (isNude)
                    continue;

            }, DispatcherPriority.Background);
        }
    }
}, ct);

但是 continue 不可用,我该怎么做?

【问题讨论】:

  • 因为它是一个 lambda 表达式,所以没有 continue,将其替换为 return。但是 continue 不会对您的程序产生任何影响,因为您可以跳过 continue 之后的任何内容。
  • @TobiasTengler continue 后存在一些我没有写的代码,如果我使用 return,它会转到 foreach 中的下一项吗?
  • 它将继续外层 foreach (var file) 中的下一项,或者更准确地说,它将在等待语句之后继续,然后跳转到下一项。
  • @TobiasTengler tnx 兄弟我的问题已解决,如果您想将其作为答案发送,我可以将其作为答案进行检查
  • 我将其添加为答案。很高兴我能帮助你。编码愉快!

标签: c# wpf loops foreach dispatcher


【解决方案1】:

正如我在评论中提到的,Dispatcher.InvokeAsync 的 lambda 不知道它是在循环中调用的,因此没有可用的 continue。您需要使用return 退出等待的任务,这样您的代码才能在等待的任务之后继续执行。

bool isNude = false;
var SearchTask = Task.Run(async () =>
{
    foreach (var file in await GetFileListAsync(GlobalData.Config.DataPath))
    {
        isNude = false;
        if (!ct.IsCancellationRequested)
        {
            await Dispatcher.InvokeAsync(() =>
            {
                if (ButtonNude.IsChecked == true)
                {
                    foreach (var itemx in nudeData)
                    {
                        if (itemx.Equals(Path.GetFileNameWithoutExtension(file.FullName)))
                        {
                            isNude = true;
                            break;
                        }
                    }
                }
                if (isNude)
                    return; // continue -> return

                // other code
                }, DispatcherPriority.Background);

                // <--- code continues here after return
            }
    }
}, ct);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多