具有 BlockingCollection 的消费者/生产者看起来很慢 [英] Consumer/Producer with BlockingCollection appears slow

查看:54
本文介绍了具有 BlockingCollection 的消费者/生产者看起来很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过下面的生产者"从外部套接字连接获取数据.

I am getting data from an external socket connection through the "Producer" below.

我将数据放入BlockingCollection,然后由消费者读取.如果消费者在固定时间内没有收到数据,它无论如何都会触发,这样我的 ProcessDataOnGrid 就会在数据到达时或至少在 x 毫秒后执行某些操作.

I place the data into a BlockingCollection, which is then read by the consumer. If the consumer does NOT receive data within a fixed period, it fires off anyway, such that my ProcessDataOnGrid, does something whenever data arrives OR AT LEAST after x millisecs.

问题是我已经读到 BlockingCollection 是首选方法,但看起来很慢.

The problem is that I have read that BlockingCollection is the preferred approach for this, BUT is appears very slow.

从获取外部数据到调用 ProcessDataOnGrid 平均间隔 150 毫秒.我是否错误地使用了它,或者有没有更好的方法来等待数据但只在固定的时间段内?

On average 150ms between when I get the external data and when I call ProcessDataOnGrid. Am I using this incorrectly, or is there a better way to wait for data BUT only for a fixed period of time?

public BlockingCollection<TickRecord> trPipe = new BlockingCollection<TickRecord>();

制作人:

public void ProcessMarketData(string key, string intraMessage)
{
    //////////
    //   Gets External data from intraMessage
    ////////////
    try
    {
        if (GRID!=null)
        {
            TickRecord tr = new TickRecord(intraMessage);

            while ( ! AddToFeedPipe(key, tr) )
            {
                Thread.Sleep(1000);
            }
        }
    }
    catch (Exception e)
    {
    }
  }
}

public bool AddToFeedPipe(string key, TickRecord tr)
{
        try
        {
            foreach (var s in cReader.STREAMS)
            {
                if (s.key == key)
                {
                    s.trPipe.Add(tr);
                    return true;
                }
            }

            return false;
        }
        catch (Exception)
        {
            return false;
        }
}

消费者:

public void Read()
{
    DateTime DTNOW = DateTime.UtcNow;

    TimeSpan gridNextTS = G.gridNextDT.Subtract(DTNOW);

    try
    {
        if (trPipe.TryTake(out tr,gridNextTS) == false)
        {
            tr = trGAP;
        }
        else if (tr == null)
        {
            EOF = true;
            return;
        }

        ProcessDataOnGrid(tr);
    }
    catch (Exception e)
    {
        tr = null;
        EOF = true;
        return;
    }
}

推荐答案

BlockingCollection 并不慢.我有另一个线程竞争相同的资源.

BlockingCollection is NOT slow. I had another thread competing for the same resource.

非常感谢.

这篇关于具有 BlockingCollection 的消费者/生产者看起来很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆