Example #1
0
        private void ThreadPoolWorker(object state)
        {
            Thread.CurrentThread.Name = "UnreliableChannel Thread";
            ThreadChecker.ConfigureUnreliable(Thread.CurrentThread);
            bool shouldRun = true;

            NetEndPoint to = new NetEndPoint();

            void SendTo(byte[] bytes, int count)
            {
                this.socket.Send(bytes, count, to);
            }

            NetEndPoint[] endPoints     = new NetEndPoint[100];
            int           endPointCount = 0;

            do
            {
                lock (this) { shouldRun = this.socket != null; }

                try {
                    this.socket.Receive();

                    if (this.sendInfoCollection.TryDequeue(out SendInfo info))
                    {
                        var message = info.message;
                        to = info.to;

                        if (!this.writerCollection.TryGetValue(to, out MessageStreamWriter writer))
                        {
                            writer = new MessageStreamWriter();
                            this.writerCollection.TryAdd(to, writer);
                            lock (this.lockToken) {
                                this.netEndPointWriters.Add(to);
                            }
                        }
                        writer.Write(message);
                    }

                    lock (this.lockToken) {
                        this.netEndPointWriters.CopyTo(endPoints);
                        endPointCount = this.netEndPointWriters.Count;
                    }

                    for (int index = 0; index < endPointCount; index++)
                    {
                        to = endPoints[index];
                        var writer = this.writerCollection[to];
                        writer.Use(SendTo);
                    }
                } catch (ObjectDisposedException) {
                    shouldRun = false;
                } catch (Exception ex) {
                    Logger.Log($"Exception thrown in ThreadPool\n{ex}");
                }
            } while (shouldRun);

            Logger.Log("UnreliableChannel ThreadPool EXITING");
            ThreadChecker.ConfigureUnreliable(null);
        }