Search Unity

GC alloc Spikes with Task.Factory.StartNew()?

Discussion in 'Scripting' started by odoluca, Aug 16, 2021.

  1. odoluca

    odoluca

    Joined:
    Nov 5, 2014
    Posts:
    28
    I am working on a project requiring alot of asyncronized processing. I need to process colormaps as often as posible but it is not possible to complete within an Update within a reasonable amount of time so I leave that work to threads to complete.

    My issue is, I have tried <new Thread().Start()> and <Task.Factory.StartNew>. In all the forums I read, Tasks are prefered over Threads, however, in my particular case, using Tasks causes GCalloc spikes much often than Threads. Is this to be expected? How can I remedy the situation?

    Please find the code and resulting profiler screens below;

    Using Tasks;
    Code (CSharp):
    1. void Update()
    2.     {
    3. if (is_completed)
    4. {
    5.                     t_mainCameraTransform = Camera.main.transform;
    6.                     Task.Factory.StartNew(GenerateAtmosphereColorMap, t_mainCameraTransform.position);
    7.                     Task.Factory.StartNew(GenerateLithosphereColorMap, t_mainCameraTransform.position);
    8.                     Task.Factory.StartNew(GenerateAquasphereColorMap, t_mainCameraTransform.position);
    9. }
    10. }
    Profiler: GCalloc in about 100 frames
    upload_2021-8-16_20-53-7.png

    Using Threads;
    Code (CSharp):
    1. void Update()
    2.     {
    3. if (is_completed)
    4. {
    5.                     t_mainCameraTransform = Camera.main.transform;
    6.                     new Thread(new ParameterizedThreadStart(GenerateLithosphereColorMap)).Start(t_mainCameraTransform.position);
    7.                     new Thread(new ParameterizedThreadStart(GenerateAtmosphereColorMap)).Start(t_mainCameraTransform.position);
    8.                     new Thread(new ParameterizedThreadStart(GenerateAquasphereColorMap)).Start(t_mainCameraTransform.position);
    9. }
    10. }
    Profiler:
    upload_2021-8-16_20-55-21.png