简体   繁体   中英

How to rewrite to Task<T> for performance gain?

I have the following code:

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

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?

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

To re-write this using the TPL would be relatively straightfoward

Task.Factory.StartNew(() => {
    // do async stuff
});

However, this doesn't making anything thread-safe this just makes sure the work is run on a separate thread. Also, whether it's going to be faster is debatable, you would need to benchmark it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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