我在 C# 中有两个不同的对象,它们公开使用流的方法。
其中一个公开了一个以 Stream 作为参数并写入流的方法,而另一个公开了一个以 Stream 作为参数并从中读取的方法。
将内容写入 MemoryStream 是不可能的,因为有太多数据无法完全保存在内存中。有没有什么办法可以将这两种方法链接起来,或者我是否必须手动编写某种适配器以插入我自己之间?
编辑:
其中一个方法如下所示,它将对象序列化为流:
object1.WriteToStream(Stream s)
另一个看起来像这样:
object2.Process(Stream input, Stream output)
第二种方法从输入流中读取数据,处理数据并将其写入另一个流。我的问题是我需要使用第二种方法来处理第一个对象的 WriteToStream
方法生成的数据。
最佳答案
是的,您可以“链接”这两种方法。 但有一些先决条件:
- 输出流(写入流的参数)必须是全局的,或者可以从两个函数访问。
- 这两个函数在不同的线程上运行,同步运行。使用 Task.Run()或不同的 Thread
- 要将其同步到线程,您可以使用 Semaphore
这里是示例代码。但这不是工作代码,它只是一个骨架
using System;
using System.Threading;
public class Example
{
// A semaphore that simulates a limited resource pool.
//
private static Semaphore _pool;
// A padding interval to make the output more orderly.
private static int _padding;
public static void Main()
{
// Create a semaphore that can satisfy up to three
// concurrent requests. Use an initial count of zero,
// so that the entire semaphore count is initially
// owned by the main program thread.
_pool = new Semaphore(0, 2);
Thread threadWrite = new Thread(new ParameterizedThreadStart(WriterThread));
Thread threadRead = new Thread(new ParameterizedThreadStart(ReadThread));
threadWrite.Start(commonStream);
threadRead.Start(commonStream);
// Wait for half a second, to allow all the
// threads to start and to block on the semaphore.
Thread.Sleep(500);
// The main thread starts out holding the entire
// semaphore count. Calling Release(3) brings the
// semaphore count back to its maximum value, and
// allows the waiting threads to enter the semaphore,
// up to three at a time.
//
Console.WriteLine("Main thread calls Release(3).");
_pool.Release(3);
Console.WriteLine("Main thread exits.");
}
private static void WriterThread(object objStream)
{
Stream stream = (Stream)objStream;
while (true)
{
// lock the semaphore, because you want to write the stream
_pool.WaitOne();
// your code goes here, to write the stream to some data, but not all
//release the pool, to indicate to the other thread, there are data in stream
_pool.Release();
if (IsAllDataWritten)
break;
}
}
private static void ReadThread(object objStream)
{
Stream stream = (Stream)objStream;
while (true)
{
// lock the semaphore, because you want to write the stream
_pool.WaitOne();
// your code goes here, to read and process the stream data
//release the pool, to indicate to the other thread, there are data in stream
_pool.Release();
if (AllDataIsReaded )
break;
}
}
}
关于使用流的 C# 链接方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37001055/