Most efficient method to update large number of objects (1,000+) in real-time

三世轮回 提交于 2019-12-05 20:58:38

Collections are best processed in one-per-thread, but there are some options:

  • In case if any process requires some long and non-fully-consuming CPU action, you are to use your method in the question, which is thread-per-action.

  • In case there are number of collections with small process action time, you might be the best to use only one thread for all of them.

There is also an influence on performance if you do synchronization between your threads. If you do, and pretty often, that might slow the speed down.

In any case, there is always a place to think, and mandatory - for benchmark different methods of processing your action. That latter option will help you understand the multitasked workflow.


In the case of some lightweight arythmetic CPU-bound operations, you are to feel free to use a thread for all of them.


Thread-per-Collection

List<List<Action>> actions = InitializeActions();

foreach(var list in actions)
{
    var listCopy = list; // Mandatory where execution is deferred.

    // Each collection is stared on different thread from thread pool.
    Task.Factory.StartNew(() =>
    {
        foreach(var action in listCopy)
        {
            action();
        }
    }
}

Thread-per-everything

// Single thread executes all the code.
List<List<Action>> actions = InitializeActions();

foreach(var list in actions)
{
    foreach(var action in listCopy)
    {
        action();
    }
}

Thread-per-action

List<List<Action>> actions = InitializeActions();

foreach(var list in actions)
{
    foreach(var action in listCopy)
    {
        // Spawn a thread on each action.
        Task.Factory.StartNew(action);
    }
}

This is of course pretty straightforward and rough, but you get the point.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!