private static void SyncThread() { try { running = 1; while (eventqueue.Count != 0) // while stuff to send { exitevent.WaitOne(10000); // wait in case others are being generated if (Exit) { break; } if (eventqueue.TryDequeue(out InaraQueueEntry firstheq)) { List <JToken> tosend = new List <JToken>() { firstheq.eventinfo }; int maxpergo = 50; bool verbose = false; // if not too many, and we have another, and the commander is the same while (tosend.Count < maxpergo && eventqueue.TryPeek(out InaraQueueEntry nextheq) && nextheq.cmdr.Nr == firstheq.cmdr.Nr) { eventqueue.TryDequeue(out nextheq); // and remove it tosend.Add(nextheq.eventinfo); verbose |= nextheq.verbose; } InaraClass inara = new InaraClass(firstheq.cmdr, firstheq.cmdrfid); string errs = inara.Send(tosend); if (errs != null) { System.Diagnostics.Debug.WriteLine("Inara reports error" + errs); firstheq?.logger("INARA Reports: " + errs); } else if (verbose) { firstheq?.logger("Sent " + tosend.Count + " events to INARA"); } } exitevent.WaitOne(30000); // space out events well if (Exit) { break; } if (eventqueue.IsEmpty) { queuedevents.WaitOne(120000); // wait for another event keeping the thread open.. Note stop also sets this } if (Exit) { break; } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message); } finally { running = 0; } }