【问题标题】:Is it possible to asynchronously enumerate over chunks of file bytes? [duplicate]是否可以异步枚举文件字节块? [复制]
【发布时间】:2018-04-21 08:51:52
【问题描述】:

我想做的是像

    /// <summary>
    /// Read zip file into chunks of bytes of largest size possible
    /// </summary>
    /// <param name="stream"></param>
    /// <returns>Enumeration of byte arrays</returns>
    private static async Task<IEnumerable<byte[]>> ChunkStreamBytes(FileStream stream)
    {
        var tasks = new List<Task<byte[]>>();
        for (long bytesRemaining = stream.Length; bytesRemaining > 0;)
        {
            int chunkSize = (int)Math.Min(bytesRemaining, int.MaxValue);
            byte[] chunk = new byte[chunkSize];
            bytesRemaining -= await stream.ReadAsync(chunk, 0, chunk.Length);
            yield return chunk;
        }
    }

但我得到了错误

...的主体不能是迭代器块,因为 Task> 不是迭代器接口类型

我想尝试await Task.WaitAll(...),其中每个任务都在读取一个块,但我不确定这些任务是否会乱序运行并搞砸我正在尝试构建的文件。由于上下文,我需要使用async-await 模式。关于正确解决方案的任何想法?

【问题讨论】:

  • Async Streams 我相信,目前建议可能包含在 C# 8.0 中:“C# 支持迭代器方法和异步方法,但不支持既是迭代器又是异步的方法方法..”
  • 这可能在 C# 8 中得到支持,现在你可以尝试 Reactive 扩展来做异步流。

标签: c# .net file asynchronous async-await


【解决方案1】:

IEnumerable&lt;T&gt; / IEnumerator&lt;T&gt; API(包括鸭子类型的等价物)本质上是同步的;你不能轻易做到async,因为它本质上解包成bool MoveNext()T Current {get;}对——两者都不是async。很快就会有很多关于async 可枚举模式的讨论,但是:不是今天。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-12
    • 2022-11-01
    • 2019-01-30
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    相关资源
    最近更新 更多