连接WriteTo Stream和ReadFrom Stream方法

时间:2017-11-20 16:05:31

标签: c# .net

我有来自两个不同第三方库的两种方法:

Task WriteToAsync(Stream stream);
Task LoadAsync(Stream stream);

我需要将数据从源WriteTo方法传输到Load方法。

目前使用下一个解决方案:

using (var stream = new MemoryStream()) {
    await source.WriteToAsync(stream);
    stream.Position = 0;
    await destination.LoadAsync(stream);
}

还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

如下面的代码所示,您可以使用管道流将数据从一个流传输到另一个,并且在您启动阅读器之前不应在编写器上使用等待。

class Program
{
   static void Main(string[] args)
   {
      ReaderDemo rd = new ReaderDemo();
      GenPrimes(rd).ContinueWith((t) => {
         if (t.IsFaulted)
            Console.WriteLine(t.Exception.ToString());
         else
            Console.WriteLine(rd.value);
      }).Wait();
   }

   static async Task GenPrimes(ReaderDemo rd)
   {
      using (var pout = new System.IO.Pipes.AnonymousPipeServerStream(System.IO.Pipes.PipeDirection.Out))
      using (var pin = new System.IO.Pipes.AnonymousPipeClientStream(System.IO.Pipes.PipeDirection.In, pout.ClientSafePipeHandle))
      {
         var writeTask = WriterDemo.WriteTo(pout);

         await rd.LoadFrom(pin);
         await writeTask;
      }
   }
}

class ReaderDemo
{
   public string value;

   public Task LoadFrom(System.IO.Stream input)
   {
      return Task.Run(() =>
      {
         using (var r = new System.IO.StreamReader(input))
         {
            value = r.ReadToEnd();
         }
      });
   }
}

class WriterDemo
{
   public static Task WriteTo(System.IO.Stream output)
   {
      return Task.Run(() => {
         using (var writer = new System.IO.StreamWriter(output))
         {
            writer.WriteLine("2");
            for (int i = 3; i < 10000; i+=2)
            {
               int sqrt = ((int)Math.Sqrt(i)) + 1;
               int factor;
               for (factor = 3; factor <= sqrt; factor++)
               {
                  if (i % factor == 0)
                     break;
               }
               if (factor > sqrt)
               {
                  writer.WriteLine("{0}", i);
               }
            }
         }
      });
   }
}