如何在InputStream接口中包装Windows.Storage.Streams.InputStream?

时间:2013-02-12 19:41:38

标签: c# .net windows-runtime iasyncoperation

我想实现一个IInputStream,它委托给另一个IInputStream并在将它返回给用户之前处理读取数据,如下所示:

using System;

using Windows.Storage.Streams;

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;

namespace Core.Crypto {
    public class RC4InputStream : IInputStream {

        public RC4InputStream(IInputStream stream, byte[] readKey) {
            _stream = stream;

            _cipher = new RC4Engine();
            _cipher.Init(false, new KeyParameter(readKey));
        }

        public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
        {
            var op = _stream.ReadAsync(buffer, count, options);
            // Somehow magically hook up something so that I can call _cipher.ProcessBytes(...)
            return op;
        }

        private readonly IInputStream _stream;
        private readonly IStreamCipher _cipher;
    }
}

我有两个不同的问题,通过搜索广泛的互联网我无法回答:

  • 在委托的ReadAsync()之后链接另一个操作的最佳方法是什么(我可以使用'await'并且可能使用AsyncInfo创建一个新的IAsyncOperation,但我不知道如何连接进度报告器等)
  • 如何访问“IBuffer”背后的数据?

1 个答案:

答案 0 :(得分:1)

您需要返回自己的IAsyncOperationWithProgress。您可以使用AsyncInfo.Run执行此操作:

public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
{
    return AsyncInfo.Run<IBuffer, uint>(async (token, progress) =>
        {
            progress.Report(0);
            await _stream.ReadAsync(buffer, count, options);
            progress.Report(50);
            // call _cipher.ProcessBytes(...)
            progress.Report(100);
            return buffer;
        });
}

当然,根据您的工作情况,您可以根据自己的工作进行更细化的报告。

要访问IBuffer中的数据,您可以使用ToArrayAsStream扩展方法。