< Summary

Information
Class: Ice.Internal.ThreadPool
Assembly: Ice
File(s): /_/csharp/src/Ice/Internal/ThreadPool.cs
Tag: 125_37167941578
Line coverage
71%
Covered lines: 236
Uncovered lines: 93
Coverable lines: 329
Total lines: 770
Line coverage: 71.7%
Branch coverage
69%
Covered branches: 113
Total branches: 162
Branch coverage: 69.7%
Method coverage
89%
Covered methods: 25
Fully covered methods: 13
Total methods: 28
Method coverage: 89.2%
Full method coverage: 46.4%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)57.14%672863.38%
destroy()50%2285.71%
updateObservers()100%22100%
initialize(...)100%11100%
register(...)100%11100%
update(...)100%1010100%
unregister(...)100%11100%
finish(...)100%22100%
executeFromThisThread(...)50%5455.56%
execute(...)50%2287.5%
joinWithAllThreads()100%22100%
get_canShrink()0%620%
QueueTask(...)100%11100%
TryExecuteTaskInline(...)50%2275%
TryDequeue(...)100%210%
GetScheduledTasks()100%210%
queueReadyForIOHandler(...)100%11100%
run(...)71.88%783264.44%
ioCompleted(...)77.78%371860.87%
startMessage(...)79.17%272483.33%
finishMessage(...)87.5%8887.5%
getCallback(...)100%11100%
.ctor(...)100%11100%
updateObserver()100%44100%
setState(...)100%44100%
join()100%11100%
start(...)50%2287.5%
Run()33.33%731225%

File(s)

/_/csharp/src/Ice/Internal/ThreadPool.cs

#LineLine coverage
 1// Copyright (c) ZeroC, Inc.
 2
 3using System.Diagnostics;
 4
 5namespace Ice.Internal;
 6
 7public delegate void ThreadPoolWorkItem(ThreadPoolCurrent current);
 8
 9public delegate void AsyncCallback(object state);
 10
 11internal class ThreadPoolMessage : IDisposable
 12{
 13    public ThreadPoolMessage(ThreadPoolCurrent current, object mutex)
 14    {
 15        _current = current;
 16        _mutex = mutex;
 17        _finish = false;
 18        _finishWithIO = false;
 19    }
 20
 21    public bool startIOScope()
 22    {
 23        // This must be called with the handler locked.
 24        _finishWithIO = _current.startMessage();
 25        return _finishWithIO;
 26    }
 27
 28    public void finishIOScope()
 29    {
 30        if (_finishWithIO)
 31        {
 32            // This must be called with the handler locked.
 33            _current.finishMessage();
 34        }
 35    }
 36
 37    public void ioCompleted()
 38    {
 39        //
 40        // Call finishMessage once IO is completed only if serialization is not enabled.
 41        // Otherwise, finishMessage will be called when the event handler is done with
 42        // the message (it will be called from Dispose below).
 43        //
 44        Debug.Assert(_finishWithIO);
 45        if (_current.ioCompleted())
 46        {
 47            _finishWithIO = false;
 48            _finish = true;
 49        }
 50    }
 51
 52    public void Dispose()
 53    {
 54        if (_finish)
 55        {
 56            //
 57            // A ThreadPoolMessage instance must be created outside the synchronization of the event handler. We
 58            // need to lock the event handler here to call finishMessage.
 59            //
 60            lock (_mutex)
 61            {
 62                _current.finishMessage();
 63            }
 64        }
 65    }
 66
 67    private readonly ThreadPoolCurrent _current;
 68    private readonly object _mutex;
 69    private bool _finish;
 70    private bool _finishWithIO;
 71}
 72
 73public class ThreadPoolCurrent
 74{
 75    internal ThreadPoolCurrent(ThreadPool threadPool, ThreadPool.WorkerThread thread)
 76    {
 77        _threadPool = threadPool;
 78        _thread = thread;
 79    }
 80
 81    public int operation;
 82
 83    public bool ioCompleted() => _threadPool.ioCompleted(this);
 84
 85    public bool startMessage() => _threadPool.startMessage(this);
 86
 87    public void finishMessage() => _threadPool.finishMessage(this);
 88
 89    internal readonly ThreadPool _threadPool;
 90    internal readonly ThreadPool.WorkerThread _thread;
 91    internal bool _ioCompleted;
 92    internal EventHandler _handler;
 93}
 94
 95public sealed class ThreadPool : System.Threading.Tasks.TaskScheduler
 96{
 197    public ThreadPool(Instance instance, string prefix, int timeout)
 98    {
 199        Ice.Properties properties = instance.initializationData().properties;
 100
 1101        _instance = instance;
 1102        _executor = instance.initializationData().executor;
 1103        _destroyed = false;
 1104        _prefix = prefix;
 1105        _threadIndex = 0;
 1106        _inUse = 0;
 1107        _serialize = properties.getPropertyAsInt(_prefix + ".Serialize") > 0;
 1108        _serverIdleTime = timeout <= 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(timeout);
 109
 1110        string programName = properties.getIceProperty("Ice.ProgramName");
 1111        if (programName.Length > 0)
 112        {
 1113            _threadPrefix = programName + "-" + _prefix;
 114        }
 115        else
 116        {
 0117            _threadPrefix = _prefix;
 118        }
 119
 1120        int size = properties.getPropertyAsIntWithDefault(_prefix + ".Size", 1);
 1121        if (size < 1)
 122        {
 0123            string s = _prefix + ".Size < 1; Size adjusted to 1";
 0124            _instance.initializationData().logger.warning(s);
 0125            size = 1;
 126        }
 127
 1128        int sizeMax = properties.getPropertyAsIntWithDefault(_prefix + ".SizeMax", size);
 1129        if (sizeMax < size)
 130        {
 1131            string s = _prefix + ".SizeMax < " + _prefix + ".Size; SizeMax adjusted to Size (" + size + ")";
 1132            _instance.initializationData().logger.warning(s);
 1133            sizeMax = size;
 134        }
 135
 1136        int sizeWarn = properties.getPropertyAsInt(_prefix + ".SizeWarn");
 1137        if (sizeWarn != 0 && sizeWarn < size)
 138        {
 0139            string s = _prefix + ".SizeWarn < " + _prefix + ".Size; adjusted SizeWarn to Size (" + size + ")";
 0140            _instance.initializationData().logger.warning(s);
 0141            sizeWarn = size;
 142        }
 1143        else if (sizeWarn > sizeMax)
 144        {
 0145            string s = _prefix + ".SizeWarn > " + _prefix + ".SizeMax; adjusted SizeWarn to SizeMax ("
 0146                + sizeMax + ")";
 0147            _instance.initializationData().logger.warning(s);
 0148            sizeWarn = sizeMax;
 149        }
 150
 1151        int threadIdleTime = properties.getPropertyAsIntWithDefault(_prefix + ".ThreadIdleTime", 60);
 1152        if (threadIdleTime < 0)
 153        {
 0154            string s = _prefix + ".ThreadIdleTime < 0; ThreadIdleTime adjusted to 0";
 0155            _instance.initializationData().logger.warning(s);
 0156            threadIdleTime = 0;
 157        }
 158
 1159        _size = size;
 1160        _sizeMax = sizeMax;
 1161        _sizeWarn = sizeWarn;
 1162        _threadIdleTime = threadIdleTime <= 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(threadIdleTime);
 163
 1164        int stackSize = properties.getPropertyAsInt(_prefix + ".StackSize");
 1165        if (stackSize < 0)
 166        {
 0167            string s = _prefix + ".StackSize < 0; Size adjusted to OS default";
 0168            _instance.initializationData().logger.warning(s);
 0169            stackSize = 0;
 170        }
 1171        _stackSize = stackSize;
 172
 1173        _priority = properties.getProperty(_prefix + ".ThreadPriority").Length > 0 ?
 1174            Util.getThreadPriorityProperty(properties, _prefix) :
 1175            Util.getThreadPriorityProperty(properties, "Ice");
 176
 1177        if (_instance.traceLevels().threadPool >= 1)
 178        {
 0179            string s = "creating " + _prefix + ": Size = " + _size + ", SizeMax = " + _sizeMax + ", SizeWarn = " +
 0180                       _sizeWarn;
 0181            _instance.initializationData().logger.trace(_instance.traceLevels().threadPoolCat, s);
 182        }
 183
 1184        _workItems = new Queue<ThreadPoolWorkItem>();
 185
 186        try
 187        {
 1188            _threads = new List<WorkerThread>();
 1189            for (int i = 0; i < _size; ++i)
 190            {
 1191                var thread = new WorkerThread(this, _threadPrefix + "-" + _threadIndex++);
 1192                thread.start(_priority);
 1193                _threads.Add(thread);
 194            }
 1195        }
 0196        catch (System.Exception ex)
 197        {
 0198            string s = "cannot create thread for `" + _prefix + "':\n" + ex;
 0199            _instance.initializationData().logger.error(s);
 200
 0201            destroy();
 0202            joinWithAllThreads();
 0203            throw;
 204        }
 1205    }
 206
 207    public void destroy()
 208    {
 1209        lock (_mutex)
 210        {
 1211            if (_destroyed)
 212            {
 0213                return;
 214            }
 1215            _destroyed = true;
 1216            Monitor.PulseAll(_mutex);
 1217        }
 1218    }
 219
 220    public void updateObservers()
 221    {
 1222        lock (_mutex)
 223        {
 1224            foreach (WorkerThread t in _threads)
 225            {
 1226                t.updateObserver();
 227            }
 228        }
 1229    }
 230
 231    public void initialize(EventHandler handler)
 232    {
 1233        handler._ready = 0;
 1234        handler._pending = 0;
 1235        handler._started = 0;
 1236        handler._finish = false;
 1237        handler._hasMoreData = false;
 1238        handler._registered = 0;
 1239    }
 240
 1241    public void register(EventHandler handler, int op) => update(handler, SocketOperation.None, op);
 242
 243    public void update(EventHandler handler, int remove, int add)
 244    {
 1245        lock (_mutex)
 246        {
 247            Debug.Assert(!_destroyed);
 248
 249            // Don't remove what needs to be added
 1250            remove &= ~add;
 251
 252            // Don't remove/add if already un-registered or registered
 1253            remove &= handler._registered;
 1254            add &= ~handler._registered;
 1255            if (remove == add)
 256            {
 1257                return;
 258            }
 259
 1260            handler._registered &= ~remove;
 1261            handler._registered |= add;
 262
 1263            if ((add & SocketOperation.Read) != 0 && (handler._pending & SocketOperation.Read) == 0)
 264            {
 1265                handler._pending |= SocketOperation.Read;
 1266                queueReadyForIOHandler(handler, SocketOperation.Read);
 267            }
 1268            else if ((add & SocketOperation.Write) != 0 && (handler._pending & SocketOperation.Write) == 0)
 269            {
 1270                handler._pending |= SocketOperation.Write;
 1271                queueReadyForIOHandler(handler, SocketOperation.Write);
 272            }
 1273        }
 1274    }
 275
 1276    public void unregister(EventHandler handler, int op) => update(handler, op, SocketOperation.None);
 277
 278    public void finish(EventHandler handler)
 279    {
 1280        lock (_mutex)
 281        {
 282            Debug.Assert(!_destroyed);
 283
 1284            handler._registered = SocketOperation.None;
 285
 286            //
 287            // If there are no pending asynchronous operations, we can call finish on the handler now.
 288            //
 1289            if (handler._pending == 0)
 290            {
 1291                _workItems.Enqueue(current =>
 1292                    {
 1293                        current.operation = SocketOperation.None;
 1294                        current._handler = handler;
 1295                        handler.finished(current);
 1296                    });
 1297                Monitor.Pulse(_mutex);
 298            }
 299            else
 300            {
 1301                handler._finish = true;
 302            }
 1303        }
 1304    }
 305
 306    public void executeFromThisThread(System.Action call, Ice.Connection connection)
 307    {
 1308        if (_executor is not null)
 309        {
 310            try
 311            {
 1312                _executor(call, connection);
 1313            }
 0314            catch (System.Exception ex)
 315            {
 0316                if (_instance.initializationData().properties.getIcePropertyAsInt("Ice.Warn.Executor") > 0)
 317                {
 0318                    _instance.initializationData().logger.warning($"executor exception:\n{ex}");
 319                }
 0320            }
 321        }
 322        else
 323        {
 1324            call();
 325        }
 1326    }
 327
 328    public void execute(Action workItem, Ice.Connection connection)
 329    {
 1330        lock (_mutex)
 331        {
 1332            if (_destroyed)
 333            {
 0334                throw new Ice.CommunicatorDestroyedException();
 335            }
 1336            _workItems.Enqueue(current =>
 1337                {
 1338                    current.ioCompleted();
 1339                    executeFromThisThread(workItem, connection);
 1340                });
 1341            Monitor.Pulse(_mutex);
 1342        }
 1343    }
 344
 345    public void joinWithAllThreads()
 346    {
 347        //
 348        // _threads is immutable after destroy() has been called, therefore no synchronization is needed.
 349        // (Synchronization wouldn't be possible here anyway, because otherwise the other threads would never
 350        // terminate.)
 351        //
 352        Debug.Assert(_destroyed);
 1353        foreach (WorkerThread thread in _threads)
 354        {
 1355            thread.join();
 356        }
 1357    }
 358
 359    // A worker thread can exit only when both conditions hold: the thread idle time is finite (so an idle worker
 360    // can time out), and the pool can have more than one worker (so a worker is eligible to be reaped without
 361    // dropping the pool below its floor of 1). Used by ConnectionI.startAsync to decide whether async I/O initiated
 362    // on an Ice worker thread needs to be hopped onto a .NET ThreadPool thread to survive the worker's exit.
 0363    public bool canShrink => _threadIdleTime != Timeout.InfiniteTimeSpan && _sizeMax > 1;
 364
 365    protected sealed override void QueueTask(
 1366        System.Threading.Tasks.Task task) => execute(
 1367            () => TryExecuteTask(task),
 1368            null);
 369
 370    protected sealed override bool TryExecuteTaskInline(System.Threading.Tasks.Task task, bool taskWasPreviouslyQueued)
 371    {
 1372        if (!taskWasPreviouslyQueued)
 373        {
 1374            executeFromThisThread(() => TryExecuteTask(task), null);
 1375            return true;
 376        }
 0377        return false;
 378    }
 379
 0380    protected sealed override bool TryDequeue(System.Threading.Tasks.Task task) => false;
 381
 382    protected sealed override IEnumerable<System.Threading.Tasks.Task> GetScheduledTasks() =>
 0383        Array.Empty<System.Threading.Tasks.Task>();
 384
 385    private void queueReadyForIOHandler(EventHandler handler, int operation)
 386    {
 1387        lock (_mutex)
 388        {
 389            Debug.Assert(!_destroyed);
 1390            _workItems.Enqueue(current =>
 1391                {
 1392                    current._handler = handler;
 1393                    current.operation = operation;
 1394                    try
 1395                    {
 1396                        current._handler.message(current);
 1397                    }
 0398                    catch (System.Exception ex)
 1399                    {
 0400                        string s = "exception in `" + _prefix + "':\n" + ex + "\nevent handler: " +
 0401                            current._handler.ToString();
 0402                        _instance.initializationData().logger.error(s);
 0403                    }
 1404                });
 1405            Monitor.Pulse(_mutex);
 1406        }
 1407    }
 408
 409    private void run(WorkerThread thread)
 410    {
 1411        var current = new ThreadPoolCurrent(this, thread);
 412        while (true)
 413        {
 1414            ThreadPoolWorkItem workItem = null;
 1415            lock (_mutex)
 416            {
 1417                while (_workItems.Count == 0)
 418                {
 1419                    if (_destroyed)
 420                    {
 1421                        return;
 422                    }
 423
 1424                    if (_threadIdleTime != Timeout.InfiniteTimeSpan)
 425                    {
 1426                        if (!Monitor.Wait(_mutex, _threadIdleTime) && _workItems.Count == 0) // If timeout
 427                        {
 1428                            if (_destroyed)
 429                            {
 0430                                return;
 431                            }
 1432                            else if (_inUse < _threads.Count - 1)
 433                            {
 0434                                if (_instance.traceLevels().threadPool >= 1)
 435                                {
 0436                                    string s = "shrinking " + _prefix + ": Size=" + (_threads.Count - 1);
 0437                                    _instance.initializationData().logger.trace(
 0438                                        _instance.traceLevels().threadPoolCat, s);
 439                                }
 440
 0441                                _threads.Remove(thread);
 0442                                _workItems.Enqueue(c =>
 0443                                        // No call to ioCompleted, this shouldn't block (and we don't want to cause
 0444                                        // a new thread to be started).
 0445                                        thread.join());
 0446                                Monitor.Pulse(_mutex);
 0447                                return;
 448                            }
 1449                            else if (_inUse > 0)
 450                            {
 451                                //
 452                                // If this is the last idle thread but there are still other threads
 453                                // busy dispatching, we go back waiting with _threadIdleTime. We only
 454                                // wait with _serverIdleTime when there's only one thread left.
 455                                //
 456                                continue;
 457                            }
 458
 459                            Debug.Assert(_threads.Count == 1);
 1460                            if (!Monitor.Wait(_mutex, _serverIdleTime) && !_destroyed)
 461                            {
 1462                                _workItems.Enqueue(c =>
 1463                                    {
 1464                                        c.ioCompleted();
 1465                                        try
 1466                                        {
 1467                                            _instance.objectAdapterFactory().shutdown();
 1468                                        }
 0469                                        catch (Ice.CommunicatorDestroyedException)
 1470                                        {
 0471                                        }
 1472                                    });
 473                            }
 474                        }
 475                    }
 476                    else
 477                    {
 0478                        Monitor.Wait(_mutex);
 479                    }
 480                }
 481
 482                Debug.Assert(_workItems.Count > 0);
 1483                workItem = _workItems.Dequeue();
 484
 1485                current._thread.setState(Ice.Instrumentation.ThreadState.ThreadStateInUseForIO);
 1486                current._ioCompleted = false;
 1487            }
 488
 489            try
 490            {
 1491                workItem(current);
 1492            }
 0493            catch (System.Exception ex)
 494            {
 0495                string s = "exception in `" + _prefix + "' while calling on work item:\n" + ex + '\n';
 0496                _instance.initializationData().logger.error(s);
 0497            }
 498
 1499            lock (_mutex)
 500            {
 1501                if (_sizeMax > 1 && current._ioCompleted)
 502                {
 503                    Debug.Assert(_inUse > 0);
 1504                    --_inUse;
 505                }
 1506                thread.setState(Ice.Instrumentation.ThreadState.ThreadStateIdle);
 1507            }
 508        }
 1509    }
 510
 511    public bool ioCompleted(ThreadPoolCurrent current)
 512    {
 1513        lock (_mutex)
 514        {
 1515            current._ioCompleted = true; // Set the IO completed flag to specify that ioCompleted() has been called.
 516
 1517            current._thread.setState(Ice.Instrumentation.ThreadState.ThreadStateInUseForUser);
 518
 1519            if (_sizeMax > 1)
 520            {
 521                Debug.Assert(_inUse >= 0);
 1522                ++_inUse;
 523
 1524                if (_sizeMax > 1 && _inUse == _sizeWarn)
 525                {
 0526                    string s = "thread pool `" + _prefix + "' is running low on threads\n"
 0527                        + "Size=" + _size + ", " + "SizeMax=" + _sizeMax + ", " + "SizeWarn=" + _sizeWarn;
 0528                    _instance.initializationData().logger.warning(s);
 529                }
 530
 1531                if (!_destroyed && _inUse < _sizeMax && _inUse == _threads.Count)
 532                {
 1533                    if (_instance.traceLevels().threadPool >= 1)
 534                    {
 0535                        string s = "growing " + _prefix + ": Size = " + (_threads.Count + 1);
 0536                        _instance.initializationData().logger.trace(_instance.traceLevels().threadPoolCat, s);
 537                    }
 538
 539                    try
 540                    {
 1541                        var t = new WorkerThread(this, _threadPrefix + "-" + _threadIndex++);
 1542                        t.start(_priority);
 1543                        _threads.Add(t);
 1544                    }
 0545                    catch (System.Exception ex)
 546                    {
 0547                        string s = "cannot create thread for `" + _prefix + "':\n" + ex;
 0548                        _instance.initializationData().logger.error(s);
 0549                    }
 550                }
 551            }
 1552        }
 1553        return _sizeMax > 1 && _serialize;
 554    }
 555
 556    public bool startMessage(ThreadPoolCurrent current)
 557    {
 558        Debug.Assert((current._handler._pending & current.operation) != 0);
 559
 1560        if ((current._handler._started & current.operation) != 0)
 561        {
 562            Debug.Assert((current._handler._ready & current.operation) == 0);
 1563            current._handler._ready |= current.operation;
 1564            current._handler._started &= ~current.operation;
 1565            if (!current._handler.finishAsync(current.operation)) // Returns false if the handler is finished.
 566            {
 1567                current._handler._pending &= ~current.operation;
 1568                if (current._handler._pending == 0 && current._handler._finish)
 569                {
 1570                    finish(current._handler);
 571                }
 1572                return false;
 573            }
 574        }
 1575        else if ((current._handler._ready & current.operation) == 0 &&
 1576                (current._handler._registered & current.operation) != 0)
 577        {
 578            Debug.Assert((current._handler._started & current.operation) == 0);
 1579            if (!current._handler.startAsync(current.operation, getCallback(current.operation)))
 580            {
 0581                current._handler._pending &= ~current.operation;
 0582                if (current._handler._pending == 0 && current._handler._finish)
 583                {
 0584                    finish(current._handler);
 585                }
 0586                return false;
 587            }
 588            else
 589            {
 1590                current._handler._started |= current.operation;
 1591                return false;
 592            }
 593        }
 594
 1595        if ((current._handler._registered & current.operation) != 0)
 596        {
 597            Debug.Assert((current._handler._ready & current.operation) != 0);
 1598            current._handler._ready &= ~current.operation;
 1599            return true;
 600        }
 601        else
 602        {
 1603            current._handler._pending &= ~current.operation;
 1604            if (current._handler._pending == 0 && current._handler._finish)
 605            {
 1606                finish(current._handler);
 607            }
 1608            return false;
 609        }
 610    }
 611
 612    public void finishMessage(ThreadPoolCurrent current)
 613    {
 1614        if ((current._handler._registered & current.operation) != 0)
 615        {
 616            Debug.Assert((current._handler._ready & current.operation) == 0);
 1617            if (!current._handler.startAsync(current.operation, getCallback(current.operation)))
 618            {
 0619                current._handler._pending &= ~current.operation;
 620            }
 621            else
 622            {
 623                Debug.Assert((current._handler._pending & current.operation) != 0);
 1624                current._handler._started |= current.operation;
 625            }
 626        }
 627        else
 628        {
 1629            current._handler._pending &= ~current.operation;
 630        }
 631
 1632        if (current._handler._pending == 0 && current._handler._finish)
 633        {
 634            // There are no more pending async operations, it's time to call finish.
 1635            finish(current._handler);
 636        }
 1637    }
 638
 639    private AsyncCallback getCallback(int operation)
 640    {
 641        Debug.Assert(operation == SocketOperation.Read || operation == SocketOperation.Write);
 1642        return state => queueReadyForIOHandler((EventHandler)state, operation);
 643    }
 644
 645    private readonly Instance _instance;
 646    private readonly System.Action<System.Action, Ice.Connection> _executor;
 647    private bool _destroyed;
 648    private readonly string _prefix;
 649    private readonly string _threadPrefix;
 650
 1651    private readonly object _mutex = new object();
 652
 653    internal sealed class WorkerThread
 654    {
 655        private readonly ThreadPool _threadPool;
 656        private Ice.Instrumentation.ThreadObserver _observer;
 657        private Ice.Instrumentation.ThreadState _state;
 658
 1659        internal WorkerThread(ThreadPool threadPool, string name)
 660        {
 1661            _threadPool = threadPool;
 1662            _name = name;
 1663            _state = Ice.Instrumentation.ThreadState.ThreadStateIdle;
 1664            updateObserver();
 1665        }
 666
 667        public void updateObserver()
 668        {
 669            // Must be called with the thread pool mutex locked
 1670            Ice.Instrumentation.CommunicatorObserver obsv = _threadPool._instance.initializationData().observer;
 1671            if (obsv is not null)
 672            {
 1673                _observer = obsv.getThreadObserver(_threadPool._prefix, _name, _state, _observer);
 1674                _observer?.attach();
 675            }
 1676        }
 677
 678        public void setState(Ice.Instrumentation.ThreadState s)
 679        {
 680            // Must be called with the thread pool mutex locked
 1681            if (_observer is not null)
 682            {
 1683                if (_state != s)
 684                {
 1685                    _observer.stateChanged(_state, s);
 686                }
 687            }
 1688            _state = s;
 1689        }
 690
 1691        public void join() => _thread.Join();
 692
 693        public void start(ThreadPriority priority)
 694        {
 1695            if (_threadPool._stackSize == 0)
 696            {
 1697                _thread = new Thread(new ThreadStart(Run));
 698            }
 699            else
 700            {
 0701                _thread = new Thread(new ThreadStart(Run), _threadPool._stackSize);
 702            }
 1703            _thread.IsBackground = true;
 1704            _thread.Name = _name;
 1705            _thread.Priority = priority;
 1706            _thread.Start();
 1707        }
 708
 709        public void Run()
 710        {
 1711            if (_threadPool._instance.initializationData().threadStart is not null)
 712            {
 713                try
 714                {
 0715                    _threadPool._instance.initializationData().threadStart();
 0716                }
 0717                catch (System.Exception ex)
 718                {
 0719                    string s = "thread hook start() method raised an unexpected exception in `";
 0720                    s += _threadPool._prefix + "' thread " + _thread.Name + ":\n" + ex;
 0721                    _threadPool._instance.initializationData().logger.error(s);
 0722                }
 723            }
 724
 725            try
 726            {
 1727                _threadPool.run(this);
 1728            }
 0729            catch (System.Exception ex)
 730            {
 0731                string s = "exception in `" + _threadPool._prefix + "' thread " + _thread.Name + ":\n" + ex;
 0732                _threadPool._instance.initializationData().logger.error(s);
 0733            }
 734
 1735            _observer?.detach();
 736
 1737            if (_threadPool._instance.initializationData().threadStop is not null)
 738            {
 739                try
 740                {
 0741                    _threadPool._instance.initializationData().threadStop();
 0742                }
 0743                catch (System.Exception ex)
 744                {
 0745                    string s = "thread hook stop() method raised an unexpected exception in `";
 0746                    s += _threadPool._prefix + "' thread " + _thread.Name + ":\n" + ex;
 0747                    _threadPool._instance.initializationData().logger.error(s);
 0748                }
 749            }
 1750        }
 751
 752        private readonly string _name;
 753        private Thread _thread;
 754    }
 755
 756    private readonly int _size; // Number of threads that are pre-created.
 757    private readonly int _sizeMax; // Maximum number of threads.
 758    private readonly int _sizeWarn; // If _inUse reaches _sizeWarn, a "low on threads" warning will be printed.
 759    private readonly bool _serialize; // True if requests need to be serialized over the connection.
 760    private readonly ThreadPriority _priority;
 761    private readonly TimeSpan _serverIdleTime;
 762    private readonly TimeSpan _threadIdleTime;
 763    private readonly int _stackSize;
 764
 765    private readonly List<WorkerThread> _threads; // All threads, running or not.
 766    private int _threadIndex; // For assigning thread names.
 767    private int _inUse; // Number of threads that are currently in use.
 768
 769    private readonly Queue<ThreadPoolWorkItem> _workItems;
 770}