Skip to main content
 首页 » 编程设计

c#之如何从任务异步返回 WCF 响应中的流

2024年02月06日15JustinYoung

我有一个类对大量数据执行一些长时间运行的处理,并将输出写入我提供的流。我正在尝试将 WCF 放在前面(使用命名管道),但无法弄清楚如何返回流。到目前为止,我有这样的事情:

interface IProcessor { Stream GetStream(); } 
 
class Host { 
  static void Main(string[] args) { 
    using (ServiceHost sh = new ServiceHost(typeof(Processor), new Uri[]{new Uri("net.pipe://localhost")})) { 
      var binding = new NetNamedPipeBinding(); 
      binding.TransferMode = TransferMode.StreamedResponse; 
      sh.AddServiceEndpoint(typeof(IProcessor), binding, "foo"); 
      sh.Open(); 
      Console.WriteLine("Waiting..."); 
      Console.ReadLine(); 
      sh.Close(); 
    } 
  } 
} 
 
class Processor : IProcessor { 
  Stream GetStream() { 
    var SourceProcessor = new SourceProcessor(...); 
    var s = new MemoryStream(); 
    new Task(() => { SourceProcessor.Run(s); }).Start(); 
    return s; 
  } 
} 
 
class Client { 
  static void Main(string[] args) { 
    Console.WriteLine("Starting..."); 
    var binding = new NetNamedPipeBinding(); 
    binding.TransferMode = TransferMode.StreamedResponse; 
    ChannelFactory<IProcessor> f = new ChannelFactory<IProcessor>(binding, new EndpointAddress("net.pipe://localhost/foo")); 
    Console.WriteLine("Creating channel..."); 
    IProcessor eps = f.CreateChannel(); 
    Console.WriteLine("Getting stream."); 
    Stream s = eps.GetStream(); 
    StreamReader sr = new StreamReader(s); 
    while (!sr.EndOfStream) Console.WriteLine(sr.ReadLine()); 
    Console.ReadLine(); 
  } 
} 

一切都在进行中,但当然没有任何源数据能够传递给客户。我对如何执行此操作感到困惑(也许我不能),因为我需要返回流并运行任务并可能等待任务完成。如果我只是在不执行任务的情况下调用 SourceProcessor.Run(s),它会阻塞和缓冲,据称,但我不确定如何让它等到任务完成,同时返回流供客户端读取...

请您参考如下方法:

问题是如果调用 Read(,WCF 会认为流已“完成”调用返回 0 个字节。 MemoryStream会很乐意这样做,如果没有可用数据,它不会阻止读取。

问题的根源是 WCF 正在读取 MemoryStream比你写它并认为它“完成”更快,修复它的方法是你需要返回不同类型的 Stream当没有可用数据时,它会阻塞而不是返回 0。 .NET 中没有内置任何东西可以执行此操作,您需要找到第 3 方类或创建自己的类(它可能很简单,就像从 MemoryStream 派生并覆盖 Read 以阻止读取直到“完成”标志已设置(参见 BlockingCollection<T> 及其 CompleteAdding() 类似行为的方法)。

为了好玩,我把它放在一起,它完全未经测试,但它可能会满足您的需要。

using System; 
using System.Collections.Concurrent; 
using System.IO; 
 
namespace Example 
{ 
    public class BufferStream : Stream 
    { 
        public BufferStream() 
        { 
            _data = new BlockingCollection<byte[]>(); 
        } 
 
 
        /// <param name="boundedCapacity">The maximum number of calls to <see cref="Write"/> that can be made without 
        /// the buffer being drained.</param> 
        public BufferStream(int boundedCapacity) 
        { 
            _data = new BlockingCollection<byte[]>(boundedCapacity); 
        } 
 
        private readonly BlockingCollection<byte[]> _data; 
        private byte[] _currentBlock = null; 
        private int _currentBlockIndex = 0; 
 
        public int BoundedCapacity { get { return _data.BoundedCapacity; } } 
 
        public int BufferedWrites { get { return _data.Count; } } 
 
        public bool IsAddingCompleted 
        { 
            get { return _data.IsAddingCompleted; } 
        } 
 
        public bool IsCompleted 
        { 
            get { return _data.IsCompleted; } 
        } 
 
        public void CompleteAdding() 
        { 
            _data.CompleteAdding(); 
        } 
 
        public override void Write(byte[] buffer, int offset, int count) 
        { 
            var localArray = new byte[count]; 
 
            //Copy the data in to a new buffer of exactly the count size. 
            Array.Copy(buffer, offset, localArray, 0, count); 
 
            _data.Add(localArray); 
        } 
 
 
        public override int Read(byte[] buffer, int offset, int count) 
        { 
            if (_currentBlock == null || _currentBlockIndex == _currentBlock.Length) 
            { 
                if (!GetNextBlock())  
                    return 0; 
            } 
 
            int minCount = Math.Min(count, _currentBlock.Length - _currentBlockIndex); 
 
            Array.Copy(_currentBlock, _currentBlockIndex, buffer, offset, minCount); 
            _currentBlockIndex += minCount; 
 
            return minCount; 
        } 
 
        /// <summary> 
        /// Loads the next block in to <see cref="_currentBlock"/>. 
        /// </summary> 
        /// <returns>True if the next block was retrieved.</returns> 
        private bool GetNextBlock() 
        { 
            if (!_data.TryTake(out _currentBlock)) 
            { 
                //The TryTake failed, the collection is empty. 
 
                //See if we are in the completed state. 
                if (_data.IsCompleted) 
                { 
                    return false; 
                } 
 
                //Wait for more data to show up. 
                try 
                { 
                    _currentBlock = _data.Take(); 
                } 
                catch (InvalidOperationException) 
                { 
                    //If the blocking collection was marked complete while we where waiting Take throws a InvalidOperationException 
                    return false; 
                } 
            } 
 
            _currentBlockIndex = 0; 
            return true; 
        } 
 
        #region Constant functions 
 
        public override bool CanRead 
        { 
            get { return true; } 
        } 
 
        public override bool CanSeek 
        { 
            get { return false; } 
        } 
 
        public override bool CanWrite 
        { 
            get { return true; } 
        } 
 
        public override void Flush() 
        { 
        } 
 
        public override long Seek(long offset, SeekOrigin origin) 
        { 
            throw new NotSupportedException(); 
        } 
 
        public override void SetLength(long value) 
        { 
            throw new NotSupportedException(); 
        } 
 
        public override long Length 
        { 
            get { throw new NotSupportedException(); } 
        } 
 
        public override long Position 
        { 
            get { throw new NotSupportedException(); } 
            set { throw new NotSupportedException(); } 
        } 
 
        #endregion 
    } 
} 

这个比派生自 MemoryStream 的优势一旦 WCF 读取了一个值,它就不再需要保留在内存中(返回 Stream 而不是 byte[] 的全部意义)