【问题标题】:Calling IAsyncEnumerable<string> before other methods在其他方法之前调用 IAsyncEnumerable<string>
【发布时间】:2022-12-14 07:17:50
【问题描述】:

美好的一天,伙计们, 请根据我正在使用的库,我正在尝试使用IAsyncEnumerable 读取文件夹中的所有文件路径。我已经能够为此创建一个方法,但我面临的挑战是,库方法

StartQueryingFromFiles(IAsyncEnumerable<string> files, CancellationToken token) 

在调用 IAsyncEnumerable 之前首先被调用。因此,值始终为空。

我该怎么做才能确保我的参数不为空。请在下面检查我的代码:

    private void btnStarts_Click(object sender, EventArgs e, Label searchLabel, TabPage page, ProgressBar bar)
    {
        try
        {
            bar.Style = ProgressBarStyle.Marquee;
            var searchPath = searchLabel.Text; //Path to folder
            var tokenSource = new CancellationTokenSource();
            var bolFinished = false;

            if (!string.IsNullOrEmpty(searchPath) && Directory.Exists(searchPath))
            {
                Task.Run(() =>
                {   
                    //The method below gets called first before the iteration                     
                    StartQueryingFromFiles(FetchAllItems(searchPath), tokenSource.Token);
                    bolFinished = true;
                });
            }
            else
            {
                MessageBox.Show("No Audio Files Found.");
            }

            if(bolFinished)
                bar.Style = ProgressBarStyle.Blocks;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    //This gets called first, its supposed to return all files, but returns nothing
    IAsyncEnumerable<string> FetchAllItems(string searchPath)
    {
        return FetchItems(searchPath);
    }

    //This is called last, I don't know why. It reads the file paths in the folder
    async IAsyncEnumerable<string> FetchItems(string searchPath)
    {
        foreach (var item in Directory.EnumerateFiles(searchPath))
        {
            await Task.Delay(100);
            System.Diagnostics.Debug.WriteLine($"{DateTime.Now.ToLongTimeString()} Reading: {item}");
            yield return item;
        }
    }

编辑: 添加了 StartQueryingFromFiles 方法

    public void StartQueryingFromFiles(IAsyncEnumerable<string> files, CancellationToken token)
    {
        _ = QueryCommandBuilder.Instance
            .BuildRealtimeQueryCommand()
            .From(files, MediaType.Audio)
            .WithRealtimeQueryConfig(config =>
            {
        // provide a success callback that will be invoked for matches that pass result entry filter
        config.SuccessCallback = result =>
                {
                    foreach (var entry in result.ResultEntries)
                    {
                        System.Diagnostics.Debug.WriteLine($"Successfully matched {entry.TrackId}");
                    }
                };

        // configure result entry filter
        config.ResultEntryFilter = new TrackMatchLengthEntryFilter(5d);
                return config;
            })
            .UsingServices(modelService, mediaService)
            .Query(token);
    }

你可以在这里获得更多关于图书馆的信息:https://github.com/AddictedCS/soundfingerprinting/wiki/Realtime-Query-Command#query-from-a-continuous-stream-of-files

谢谢

【问题讨论】:

  • 你能包括StartQueryingFromFiles方法吗?
  • 谢谢@TheodorZoulias,我现在将编辑并包含它。谢谢
  • 这段代码真的可以从 async 安排中获益,如 await FetchAllItems(searchPath)
  • 感谢@RobertHarvey,如果您将 FetchAllItems 设置为异步等待,那么它不会返回所有项目,而是一个接一个地返回项目。即使就我而言,它不是连续的。我只得到一个项目,此时没有任何内容传递给 StartQueryingFromFiles 方法

标签: c# parallel-processing task iasyncenumerable


【解决方案1】:

好的,经过大量研究,感谢这些人:https://www.dotnetcurry.com/csharp/async-streams

我能够看到我可以使用 System.Linq.Async 将我的文件转换为 IAsyncEnumerable。

因此,不需要编写上面所有的 FetchItems 方法。 我只需要执行以下操作:

Task.Run(() =>
{
     DirectoryInfo di = new DirectoryInfo(searchPath);
     var getAllFiles = di.GetFiles()
           .Where(file => file.Name.EndsWith(".mp3"))
           .Select(file => file.Name).ToAsyncEnumerable<string>();

      StartQueryingFromFiles(getAllFiles, tokenSource.Token);
      bolFinished = true;
  });

因此能够将所有文件放入一个 IAsyncEnumerable 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多