【发布时间】:2015-03-15 01:56:18
【问题描述】:
我想向 WCF 服务发送一个数据流(大文件 > 2GB),对其进行处理,然后将处理后的数据作为流(transferMode = "Streamed")返回,而不是在内存中缓冲整个流然后发送它返回。
我知道传统的流式数据输入和输出方法(在 WCF 操作之外)涉及
- 在消费端,以输入 Stream 和输出 Stream 作为参数将流发送到(WCF 服务)void 方法。
- 在消费端,也有一个接收流来获取 传入,处理后的输出流
- 在该方法中,处理输入 Stream 然后写入 处理后的字节到输出流
- 那些处理过的字节是通过输出流接收到的
这样,水流不会中断。
例如来自 Microsoft 示例:
void CopyStream(System.IO.Stream instream, System.IO.Stream outstream)
{
//read from the input stream in 4K chunks
//and save to output stream
const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = instream.Read(buffer, 0, bufferLen)) > 0)
{
outstream.Write(buffer, 0, count);
}
}
我也想这样做,只是 outputstream 将是 WCF 返回类型。那可能吗?我该如何使用transferMode = "Streamed"?
使用 WCF,当你想使用 transferMode = "Streamed" 时,不能有多个参数(或消息合约对象)Stream 类型
假设,使用这样的伪代码:
Stream StreamAndReturn(System.IO.Stream instream)
{
Stream outstream = new MemoryStream();//instantiate outstream - probably should be buffered?
while ((count = instream.Read(buffer, 0, bufferLen)) > 0)
{
//some operation on instream that will
SomeOperation(instream,outstream);
}
return outstream; //obviously this will close break the streaming
}
我还尝试了NetTcpBinding,将SessionMode 设置为SessionMode.Allowed,希望有一个可以启动的会话,将流数据发送到服务,在单独的流中获取结果,然后使用 OperationContext,检索将与该服务实例关联的任何属性。但它没有保留会话信息,见下图:
According to MSDN documentation 我还应该设置InstanceContextMode = InstanceContextMode.PerSession 和ConcurrencyMode = ConcurrencyMode.Multiple(见最后一段)
For that, I Asked a question on SO,但仍在等待答复。我在想也许有更好的方法。
【问题讨论】: