简体   繁体   English

如何重写任务 <T> 性能提升?

[英]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? 我怎么写这个来使用T的任务并仍然确保它的线程安全且快速? Or is there a better/faster way? 还是有更好/更快的方式?

I think you only need 2 threads/tasks. 我认为你只需要2个线程/任务。 1 Producer and 1 Consumer. 1名制片人和1名消费者。

//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 使用TPL重写这一点会相对简单

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. 此外,它是否会更快是有争议的,你需要对它进行基准测试。

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

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