如何重写到 Task<T>为了性能提升?

如何重写到 Task<T>为了性能提升?

问题描述:

我有以下代码:

    static BlockingCollection<SimpleObject> sendQueue = new BlockingCollection<SimpleObject>();

    static public void Insert(string key, T value)
    {
        SimpleObject simpleObject = new SimpleObject {Key = key, Value = value};
        sendQueue.Add(simpleObject);
        var data = sendQueue.Take(); //this blocks if there are no items in the queue.

        ThreadPool.QueueUserWorkItem(state =>
        {
            //Do ASYNC stuff with data here - threadsafe
        });
    }

我如何编写它以使用 T 的任务并仍然确保它是线程安全且快速的?或者有更好/更快的方法吗?

How can I write this to use Task of T and still make sure it's threadsafe and fast? Or is there a better/faster way?

我认为你只需要 2 个线程/任务.1 个生产者和 1 个消费者.

I think you only need 2 threads/tasks. 1 Producer and 1 Consumer.

//Producer
Task.Factory.StartNew(() =>
    {
        for(int i=0;i<100000000;i++)
        {
            sendQueue.Add(new SimpleObject() { Key = "", Value = "" });
        }
        sendQueue.CompleteAdding();
    });

//Consumer
Task.Factory.StartNew(() =>
    {
        foreach(var so in sendQueue.GetConsumingEnumerable())
        {
            //do something
        }
    });