如何在IInputStream接口中包装Windows.Storage.Streams.InputStream
本文关键字:Windows Storage Streams InputStream 包装 IInputStream 接口 | 更新日期: 2023-09-27 17:58:55
我想实现一个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()之后,链接另一个操作以运行的最佳方式是什么(我可以使用"wait",也可以使用AsyncInfo创建一个新的IAsyncOperation,但我不知道如何连接进度报告器等)
- 如何访问"IBuffer"后面的数据
您需要返回自己的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
中的数据,可以使用ToArray
或AsStream
扩展方法。