简体   繁体   English

线程安全的异步字节队列

[英]Thread-safe async byte queue

I've got a callback method that is called whenever new data is available: 我有一个回调方法,只要有新数据就会调用它:

public delegate void DataCallback(
    byte[] buffer,
    int offset,
    int count);

I want to wrap this in a class that implements an interface similar to this: 我想将它包装在一个实现类似于此的接口的类中:

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);
}

This is obviously a classical producer-consumer problem: the bytes are produced by calls to the callback method, and consumed by the Begin/EndRead and Read methods. 这显然是一个典型的生产者 - 消费者问题:字节是通过调用回调方法产生的,并由Begin / EndRead和Read方法使用。 The Begin/EndRead and Read methods should block if no data is available (until a timeout occurs). 如果没有可用的数据,则应该阻止Begin / EndRead和Read方法(直到发生超时)。 The implementation should use a fixed-size internal buffer, so the callback method needs to block when the buffer is currently full. 实现应该使用固定大小的内部缓冲区,因此当缓冲区当前已满时,回调方法需要阻塞。

Since thinking about multithreading usually results in a severe headache, my question is: Is there already an implementation of such a data structure? 由于考虑多线程通常会导致严重的问题,我的问题是: 是否已经实现了这样的数据结构?

(I think implementing the Read method should be quite simple, but I'd like to avoid implementing Begin/EndRead with Read. Begin / EndInvoke .) (我想实现的读法应该是很简单的,但我想,以避免执行开始/ EndRead与读取。 Begin / EndInvoke 。)

Does it have to be async via IAsyncResult ? 是否必须通过IAsyncResult异步? I have a generic blocking queue here (ie readers block until there is data or it is closed; writers block until there is space); 这里有一个通用的阻塞队列(即读取器阻塞直到有数据或它被关闭;写入器阻塞直到有空间); it isn't optimised specifically for byte[] , but as long as the size isn't vast it should cope - but as a blocking queue it requires (at least one) dedicated consumer thread, doing: 它没有专门针对byte[]进行优化,但只要大小不大就应该应对 - 但作为阻塞队列,它需要(至少一个)专用的消费者线程,执行:

T val;
while(queue.TryDequeue(out val)) {
    // process val
}

I think you should do a google search on "lockless queue". 我认为你应该在“无锁队列”上进行谷歌搜索。 I got lots of usefull hits that way. 我有很多有用的点击方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM