commodore73

Threadlist

Jul 22nd, 2020
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.10 KB | None | 0 0
  1. namespace Deliverystack.Core.Threading
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Threading;
  6.     using System.Threading.Tasks;
  7.  
  8.     public class ThreadList
  9.     {
  10.         public bool ThreadingDisabled { get; private set; }
  11.  
  12.         public bool UseTasks { get; private set; }
  13.  
  14.         private List<Thread> _threads = null;
  15.  
  16.         private List<Task> _tasks = null;
  17.  
  18.         private ThreadList()
  19.         {
  20.             throw new NotImplementedException("Pass bool disableThreading (default false)");
  21.         }
  22.  
  23.         public ThreadList(bool disableThreading, bool useTasks)
  24.         {
  25.             ThreadingDisabled = disableThreading;
  26.             UseTasks = useTasks;
  27.  
  28.             if (!ThreadingDisabled)
  29.             {
  30.                 if (UseTasks)
  31.                 {
  32.                     _tasks = new List<Task>();
  33.                 }
  34.                 else
  35.                 {
  36.                     _threads = new List<Thread>();
  37.                 }
  38.  
  39.             }
  40.         }
  41.  
  42.         public void Add(Action action, bool isForeground = false, bool disableThreading = false)
  43.         {
  44.             if (ThreadingDisabled || disableThreading)
  45.             {
  46.                 action();
  47.             }
  48.             else
  49.             {
  50.                 if (UseTasks)
  51.                 {
  52.                     _tasks.Add(Task.Factory.StartNew(action));
  53.                 }
  54.                 else
  55.                 {
  56.                     Thread thread = new Thread((t) => action());
  57.                     thread.IsBackground = !isForeground;
  58.                     thread.Start();
  59.                     _threads.Add(thread);
  60.                 }
  61.             }
  62.         }
  63.  
  64.         public void JoinAll()
  65.         {
  66.             if (_threads != null)
  67.             {
  68.                 foreach (Thread thread in _threads)
  69.                 {
  70.                     thread.Join();
  71.                 }
  72.             }
  73.  
  74.             if (_tasks != null)
  75.             {
  76.                 foreach (Task task in _tasks)
  77.                 {
  78.                     task.Wait();
  79.                 }
  80.             }
  81.         }
  82.     }
  83. }
Add Comment
Please, Sign In to add comment