【发布时间】:2010-10-27 22:59:36
【问题描述】:
我有一个回调方法,每当有新数据可用时就会调用它:
public delegate void DataCallback(
byte[] buffer,
int offset,
int count);
我想把它包装在一个实现类似这样的接口的类中:
public interface IDataSource
{
IAsyncResult BeginRead(
byte[] buffer,
int offset,
int size,
TimeSpan timeout,
AsyncCallback callback,
object state);
int EndRead(
IAsyncResult asyncResult);
int Read(
byte[] buffer,
int offset,
int size,
TimeSpan timeout);
}
这显然是一个经典的生产者-消费者问题:字节由回调方法调用产生,并由 Begin/EndRead 和 Read 方法消耗。如果没有数据可用,Begin/EndRead 和 Read 方法应该阻塞(直到发生超时)。实现应该使用一个固定大小的内部缓冲区,所以当缓冲区满时回调方法需要阻塞。
考虑到多线程通常会让人头疼,所以我的问题是:是否已经实现了这样的数据结构?
(我认为实现 Read 方法应该很简单,但我想避免使用 Read 实现 Begin/EndRead。Begin/EndInvoke。)
【问题讨论】:
标签: c# multithreading .net-3.5 queue producer-consumer