Exemplo n.º 1
0
 public void SaveConfig()
 {
     Configuration.Items            = CopyAndStripItems(items);
     Configuration.Inject           = injectChat;
     Configuration.Extender         = chatWindow;
     Configuration.Alpha            = alpha;
     Configuration.ChanColour       = chanColour.ToArray();
     Configuration.LogColour        = logColour.ToArray();
     Configuration.RTr              = rTr.ToString();
     Configuration.LTr              = lTr.ToString();
     Configuration.NoMouse          = no_mouse;
     Configuration.NoMouse2         = no_mouse2;
     Configuration.NoMove           = no_move;
     Configuration.NoResize         = no_resize;
     Configuration.Space_Hor        = space_hor;
     Configuration.Space_Ver        = space_ver;
     Configuration.TimeColour       = timeColour;
     Configuration.NameColour       = nameColour;
     Configuration.High             = high;
     Configuration.Chan             = Chan.ToArray();
     Configuration.YandexKey        = yandex.ToString();
     Configuration.Translator       = translator;
     Configuration.AllowTranslation = allowTranslation;
     Configuration.BubbleColour     = bubbleColour.ToArray();
     Configuration.BubbleEnable     = bubbleEnable.ToArray();
     Configuration.BubblesWindow    = bubblesWindow;
     Configuration.FontSize         = fontsize;
     Configuration.HourTime         = hourTime;
     Configuration.FontShadow       = fontShadow;
     Configuration.BubbleTime       = bubbleTime;
     this.pluginInterface.SavePluginConfig(Configuration);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Conn"/> class.
        /// </summary>
        public Conn(string addr, Config config, IConnDelegate connDelegate)
        {
            if (string.IsNullOrEmpty(addr))
            {
                throw new ArgumentNullException("addr");
            }
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (connDelegate == null)
            {
                throw new ArgumentNullException("connDelegate");
            }

            _addr = addr;

            _config   = config.Clone();
            _delegate = connDelegate;

            _maxRdyCount      = 2500;
            _lastMsgTimestamp = DateTime.Now.UnixNano();

            _cmdChan         = new Chan <Command>();
            _msgResponseChan = new Chan <msgResponse>();
            _exitChan        = new Chan <int>();
            _drainReady      = new Chan <int>();
        }
Exemplo n.º 3
0
 public void LeaveChannels(string PlayerName)
 {
     foreach (Channel Chan in Channels.Values.ToArray())
     {
         Chan.Remove(PlayerName);
     }
 }
Exemplo n.º 4
0
        private void BenchmarkTcp(int parallel)
        {
            string topicName = "test_benchmark_" + DateTime.Now.UnixNano();

            try
            {
                const int benchmarkNum = 30000;

                byte[] body = new byte[512];

                var p = new Producer("127.0.0.1:4150");
                p.Connect();

                var startCh = new Chan <bool>();
                var wg      = new WaitGroup();

                for (int j = 0; j < parallel; j++)
                {
                    wg.Add(1);
                    GoFunc.Run(() =>
                    {
                        startCh.Receive();
                        for (int i = 0; i < benchmarkNum / parallel; i++)
                        {
                            p.Publish(topicName, body);
                        }
                        wg.Done();
                    }, "ProducerBenchmarkTcpTest: sendLoop");
                }

                var stopwatch = Stopwatch.StartNew();
                startCh.Close();

                var done = new Chan <bool>();
                GoFunc.Run(() => { wg.Wait(); done.Send(true); }, "waiter and done sender");

                bool finished = false;
                Select
                .CaseReceive(done, b => finished = b)
                .CaseReceive(Time.After(TimeSpan.FromSeconds(10)), b => finished = false)
                .NoDefault();

                stopwatch.Stop();

                if (!finished)
                {
                    Assert.Fail("timeout");
                }

                Console.WriteLine(string.Format("{0:#,0} sent in {1:mm\\:ss\\.fff}; Avg: {2:#,0} msgs/s; Threads: {3}",
                                                benchmarkNum, stopwatch.Elapsed, benchmarkNum / stopwatch.Elapsed.TotalSeconds, parallel));

                p.Stop();
            }
            finally
            {
                _nsqdHttpClient.DeleteTopic(topicName);
                _nsqLookupdHttpClient.DeleteTopic(topicName);
            }
        }
Exemplo n.º 5
0
        public void SelectTwoChannels()
        {
            var c1 = new Chan <int>();
            var c2 = new Chan <int>();

            var t1 = new Thread(() =>
            {
                Thread.Sleep(10);
                c1.Send(1);
            });

            t1.IsBackground = true;

            var t2 = new Thread(() => c2.Send(2));

            t2.IsBackground = true;

            var list = new List <int>();

            t2.Start();
            t1.Start();

            Select
            .CaseReceive(c1, list.Add)
            .CaseReceive(c2, list.Add)
            .NoDefault();

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual(2, list[0], "list[0]");
        }
Exemplo n.º 6
0
 public MockProducerConn(IConnDelegate connDelegate)
 {
     _connDelegate = connDelegate;
     _closeCh      = new Chan <bool>();
     _pubCh        = new Chan <bool>();
     GoFunc.Run(router, "ProducerTest:router");
 }
Exemplo n.º 7
0
        public void ClosedChannelsWithDataShouldNotReportClosedUntilDrained()
        {
            for (var i = 0; i < 10000; i++)
            {
                var chan = new Chan <int>();

                var wait = new AutoResetEvent(false);

                GoFunc.Run(() =>
                {
                    chan.Send(1);
                    chan.Close();
                }, "send");

                bool ok = false, ok2 = false;
                int  actual = -1, actual2 = -1;

                GoFunc.Run(() =>
                {
                    actual  = chan.ReceiveOk(out ok);
                    actual2 = chan.ReceiveOk(out ok2);
                    wait.Set();
                }, "receive");

                wait.WaitOne();

                Assert.AreEqual(true, ok, string.Format("ok iteration {0}", i));
                Assert.AreEqual(1, actual, string.Format("actual iteration {0}", i));
                Assert.AreEqual(false, ok2, string.Format("ok2 iteration {0}", i));
                Assert.AreEqual(default(int), actual2, string.Format("actual2 iteration {0}", i));
            }
        }
Exemplo n.º 8
0
        public void SelectSendAndReceiveSendReady()
        {
            var c1 = new Chan <int>();
            var c2 = new Chan <int>();

            var t1 = new Thread(() => c1.Send(1));

            t1.IsBackground = true;

            var list = new List <int>();

            var t2 = new Thread(() =>
            {
                Thread.Sleep(50);
                list.Add(c2.Receive());
            });

            t2.IsBackground = true;

            t1.Start();
            t2.Start();

            Select
            .CaseReceive(c1, list.Add)
            .CaseSend(c2, 2, () => { })
            .NoDefault();

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual(1, list[0], "list[0]");
        }
Exemplo n.º 9
0
        public void TwoSelectsSendAndReceiveCanTalk()
        {
            var c = new Chan <int>();

            var actual = 0;

            var wg = new WaitGroup();

            wg.Add(2);

            GoFunc.Run(() =>
            {
                Select
                .CaseSend(c, 7)
                .NoDefault();

                wg.Done();
            }, "sender");

            GoFunc.Run(() =>
            {
                Select
                .CaseReceive(c, o => actual = o)
                .NoDefault();

                wg.Done();
            }, "receiver");

            wg.Wait();

            Assert.AreEqual(7, actual);
        }
Exemplo n.º 10
0
        public void SelectSendsOnly()
        {
            var c1 = new Chan <int>();
            var c2 = new Chan <int>();

            var t1 = new Thread(() =>
            {
                Thread.Sleep(1000);
                c1.Receive();
            });

            t1.IsBackground = true;

            var t2 = new Thread(() => c2.Receive());

            t2.IsBackground = true;

            var list = new List <int>();

            t1.Start();
            t2.Start();

            Select
            .CaseSend(c1, 1, () => list.Add(1))
            .CaseSend(c2, 2, () => list.Add(2))
            .NoDefault();

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual(2, list[0], "list[0]");
        }
Exemplo n.º 11
0
        public void SingleNumberGeneratorIEnumerableChan()
        {
            var c = new Chan <int>();

            var t = new Thread(() =>
            {
                for (var i = 0; i < 10; i++)
                {
                    c.Send(i);
                }
                c.Close();
            });

            t.IsBackground = true;
            t.Start();

            var list = new List <int>();

            foreach (var i in (IEnumerable)c)
            {
                list.Add((int)i);
            }

            AssertHelper.AreEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, list);
        }
Exemplo n.º 12
0
        /// <summary>
        ///     <para>Publishes a message <paramref name="body"/> to the specified <paramref name="topic"/>
        ///     but does not wait for the response from nsqd.</para>
        ///
        ///     <para>When the Producer eventually receives the response from nsqd, the Task will return a
        ///     <see cref="ProducerResponse"/> instance with the supplied <paramref name="args"/> and the response error if
        ///     present.</para>
        /// </summary>
        /// <param name="topic">The topic to publish to.</param>
        /// <param name="body">The message body.</param>
        /// <param name="args">A variable-length parameters list containing arguments. These arguments will be returned on
        ///     <see cref="ProducerResponse.Args"/>.
        /// </param>
        /// <returns>A Task&lt;ProducerResponse&gt; which can be awaited.</returns>
        public Task <ProducerResponse> PublishAsync(string topic, byte[] body, params object[] args)
        {
            var doneChan = new Chan <ProducerResponse>();

            sendCommandAsync(Command.Publish(topic, body), doneChan, args);
            return(Task.Factory.StartNew(() => doneChan.Receive()));
        }
Exemplo n.º 13
0
        public void SelectDefaultCaseChannelReady()
        {
            var c1 = new Chan <int>();
            var c2 = new Chan <int>();

            var t1 = new Thread(() =>
            {
                Thread.Sleep(100);
                c1.Send(1);
            });

            t1.IsBackground = true;

            var t2 = new Thread(() => c2.Send(5));

            t2.IsBackground = true;

            var list = new List <int>();

            t1.Start();
            t2.Start();

            Thread.Sleep(50);

            Select
            .CaseReceive(c1, list.Add)
            .CaseReceive(c2, list.Add)
            .Default(() => list.Add(3));

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual(5, list[0], "list[0]");
        }
Exemplo n.º 14
0
        /// <summary>
        /// DialTimeout acts like Dial but takes a timeout. The timeout includes name resolution, if required.
        /// </summary>
        public static IConn DialTimeout(string network, string address, TimeSpan timeout)
        {
            if (network != "tcp")
                throw new ArgumentException("only 'tcp' network is supported", "network");

            var dialChan = new Chan<IConn>();
            var timeoutChan = Time.After(timeout);

            GoFunc.Run(() =>
            {
                try
                {
                    var tmpConn = Dial(network, address);
                    dialChan.Send(tmpConn);
                }
                catch
                {
                    // handling timeout below, don't bring down the whole app with an unhandled thread exception
                }
            }, "Net:DialTimeout");

            IConn conn = null;

            Select
                .CaseReceive(dialChan, c => conn = c)
                .CaseReceive(timeoutChan, o =>
                {
                    throw new TimeoutException(string.Format("timeout {0} exceed when dialing {1}", timeout, address));
                })
                .NoDefault();

            timeoutChan.Close();

            return conn;
        }
Exemplo n.º 15
0
        public void SendOnClosedChannelThrows()
        {
            var c = new Chan <int>();

            c.Close();

            c.Send(1);
        }
Exemplo n.º 16
0
        /// <summary>
        ///     <para>Publishes a collection of message <paramref name="bodies"/> to the specified <paramref name="topic"/>
        ///     but does not wait for the response from nsqd.</para>
        ///
        ///     <para>When the Producer eventually receives the response from nsqd, the Task will return a
        ///     <see cref="ProducerResponse"/> instance with the supplied <paramref name="args"/> and the response error if
        ///     present.</para>
        /// </summary>
        /// <param name="topic">The topic to publish to.</param>
        /// <param name="bodies">The collection of message bodies.</param>
        /// <param name="args">A variable-length parameters list containing arguments. These arguments will be returned on
        ///     <see cref="ProducerResponse.Args"/>.
        /// </param>
        /// <returns>A Task&lt;ProducerResponse&gt; which can be awaited.</returns>
        public Task <ProducerResponse> MultiPublishAsync(string topic, IEnumerable <byte[]> bodies, params object[] args)
        {
            var doneChan = new Chan <ProducerResponse>();
            var cmd      = Command.MultiPublish(topic, bodies);

            sendCommandAsync(cmd, doneChan, args);
            return(Task.Factory.StartNew(() => doneChan.Receive()));
        }
Exemplo n.º 17
0
        public void SendOnClosedChannelThrows()
        {
            var c = new Chan <int>();

            c.Close();

            Assert.Throws <ChannelClosedException>(() => c.Send(1));
        }
Exemplo n.º 18
0
        public void BufferedChannelsDontBlock()
        {
            var c = new Chan<int>(1);
            c.Send(2);
            int actual = c.Receive();

            Assert.AreEqual(2, actual);
        }
Exemplo n.º 19
0
        public void BufferedChannelsDontBlock()
        {
            var c = new Chan <int>(1);

            c.Send(2);
            var actual = c.Receive();

            Assert.AreEqual(2, actual);
        }
Exemplo n.º 20
0
 // main thread
 public void Init(Chan chan)
 {
     if (onInit != null)
     {
         DH.DHExchange(out secretSend, out modpowerSend);
         DH.DHExchange(out secretRecv, out modpowerRecv);
         onInit.Invoke(chan, modpowerSend, modpowerRecv);
     }
 }
Exemplo n.º 21
0
        public void TestTickerLoopWithNemesisChan()
        {
            var start  = DateTime.Now;
            var ticker = new Ticker(TimeSpan.FromSeconds(1));

            var listOfTimes        = new List <TimeSpan>();
            var exitChan           = new Chan <bool>();
            var lookupdRecheckChan = new Chan <bool>();
            var doLoop             = true;

            using (var select =
                       Select
                       .CaseReceive(ticker.C,
                                    o =>
            {
                Console.WriteLine("Received tick");
                listOfTimes.Add(DateTime.Now - start);

                if (listOfTimes.Count == 5)
                {
                    GoFunc.Run(() => lookupdRecheckChan.Send(true), "lookupd recheck sender");
                }
            })
                       .CaseReceive(lookupdRecheckChan,
                                    o =>
            {
                Console.WriteLine("Nemesis");
                Thread.Sleep(5000);
            })
                       .CaseReceive(exitChan, o => doLoop = false)
                       .NoDefault(true))
            {
                // ReSharper disable once LoopVariableIsNeverChangedInsideLoop
                while (doLoop)
                {
                    select.Execute();
                    if (listOfTimes.Count >= 10)
                    {
                        GoFunc.Run(() => exitChan.Send(true), "exit notifier");
                    }
                }
            }

            ticker.Stop();

            var duration = DateTime.Now - start;

            Console.WriteLine("Duration: {0}", duration);
            foreach (var time in listOfTimes)
            {
                Console.WriteLine("Tick: {0}", time);
            }

            Assert.AreEqual(10, listOfTimes.Count, "listOfTimes.Count");
            AssertHelper.GreaterOrEqual(duration, TimeSpan.FromSeconds(14) - AcceptableError, "duration");
            AssertHelper.Less(duration, TimeSpan.FromSeconds(17));
        }
Exemplo n.º 22
0
        public void ReceiveOnClosedChannelReturnsDefault()
        {
            var c = new Chan <int>();

            c.Close();

            var val = c.Receive();

            Assert.AreEqual(default(int), val);
        }
Exemplo n.º 23
0
        public void GetThreadAsync()
        {
            var threadPage   = Chan.GetThreadPage("a", 1);
            var threadNumber = threadPage.Threads.First().Posts.First().PostNumber;


            var thread = Chan.GetThread("a", threadNumber);

            NotNull(thread);
        }
Exemplo n.º 24
0
 public mockNSQD(instruction[] script, IPAddress addr, int port)
 {
     this.script = script;
     exitChan    = new Chan <int>();
     got         = new List <byte[]>();
     gotTime     = new List <DateTime>();
     ipAddr      = addr;
     listenPort  = port;
     GoFunc.Run(listen, "mockNSQD:listen");
 }
Exemplo n.º 25
0
        private void tmrConvert_Tick(object eventSender, System.EventArgs eventArgs)
        {
            float  EngUnits;
            double HighResEngUnits;

            MccDaq.ErrorInfo ULStat;
            System.UInt16    DataValue;
            System.UInt32    DataValue32;
            int Chan;
            int Options = 0;

            tmrConvert.Stop();

            //  Collect the data by calling AIn member function of MccBoard object
            //   Parameters:
            //     Chan       :the input channel number
            //     Range      :the Range for the board.
            //     DataValue  :the name for the value collected

            //  set input channel
            bool ValidChan = int.TryParse(txtNumChan.Text, out Chan);

            if (ValidChan)
            {
                if (Chan > HighChan)
                {
                    Chan = HighChan;
                }
                txtNumChan.Text = Chan.ToString();
            }

            if (ADResolution > 16)
            {
                ULStat = DaqBoard.AIn32(Chan, Range, out DataValue32, Options);
                //  Convert raw data to Volts by calling ToEngUnits
                //  (member function of MccBoard class)
                ULStat = DaqBoard.ToEngUnits32(Range, DataValue32, out HighResEngUnits);

                lblShowData.Text  = DataValue32.ToString();                    //  print the counts
                lblShowVolts.Text = HighResEngUnits.ToString("F5") + " Volts"; //  print the voltage
            }
            else
            {
                ULStat = DaqBoard.AIn(Chan, Range, out DataValue);

                //  Convert raw data to Volts by calling ToEngUnits
                //  (member function of MccBoard class)
                ULStat = DaqBoard.ToEngUnits(Range, DataValue, out EngUnits);

                lblShowData.Text  = DataValue.ToString();               //  print the counts
                lblShowVolts.Text = EngUnits.ToString("F4") + " Volts"; //  print the voltage
            }

            tmrConvert.Start();
        }
Exemplo n.º 26
0
        public void PrimeSieve()
        {
            var generate = new Action <Chan <int> >(cgen =>
            {
                while (true)
                {
                    for (var i = 2; ; i++)
                    {
                        cgen.Send(i);
                    }
                }
                // ReSharper disable once FunctionNeverReturns
            });

            var filter = new Action <Chan <int>, Chan <int>, int>((cin, cout, prime) =>
            {
                while (true)
                {
                    var i = cin.Receive();
                    if (i % prime != 0)
                    {
                        cout.Send(i);
                    }
                }
                // ReSharper disable once FunctionNeverReturns
            });

            var ch = new Chan <int>();

            var generateCh     = ch;
            var threadGenerate = new Thread(() => generate(generateCh));

            threadGenerate.IsBackground = true;
            threadGenerate.Start();

            var list = new List <int>();

            for (var i = 0; i < 10; i++)
            {
                var prime = ch.Receive();
                list.Add(prime);

                var ch0 = ch;
                var ch1 = new Chan <int>();

                var threadFilter = new Thread(() => filter(ch0, ch1, prime));
                threadFilter.IsBackground = true;
                threadFilter.Start();

                ch = ch1;
            }

            AssertHelper.AreEqual(new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }, list);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Creates a channel which fires after the specified timeout.
        /// </summary>
        public static Chan <bool> After(TimeSpan timeout)
        {
            if (timeout < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("timeout", timeout, "timeout must be >= 0");
            }

            var timeoutChan = new Chan <bool>();

            var started = DateTime.Now;

            System.Threading.Timer localTimer = null;
            System.Threading.Timer t          = new System.Threading.Timer(
                delegate
            {
                string threadName         = string.Format("Time.After started:{0} duration:{1}", started, timeout);
                Thread.CurrentThread.Name = threadName;
                try
                {
                    if (localTimer != null)
                    {
                        lock (_threadingTimersLocker)
                        {
                            _threadingTimers.Remove(localTimer);
                            localTimer.Dispose();
                            localTimer = null;
                        }
                    }
                }
                catch { }

                try
                {
                    if (!((IChan)timeoutChan).IsClosed)
                    {
                        timeoutChan.Send(default(bool));
                    }
                }
                catch { }
            }, null, timeout, TimeSpan.FromMilliseconds(-1));

            localTimer = t;

            lock (_threadingTimersLocker)
            {
                if (localTimer != null)
                {
                    _threadingTimers.Add(localTimer);
                }
            }

            return(timeoutChan);
        }
Exemplo n.º 28
0
 public void GetThreadPage()
 {
     try
     {
         ThreadRootObject thread = Chan.GetThreadPage("a", 1);
         Assert.NotNull(thread);
     }
     catch (Exception e)
     {
         Assert.Fail(e.Message);
     }
 }
Exemplo n.º 29
0
        public void UnbufferChannel1()
        {
            var  ch = new Chan <int>();
            Task t  = Task.Run(() =>
            {
                Thread.Sleep(10);
                ch.Send(1);
            });
            var result = ch.Receive();

            Assert.AreEqual(result, 1);
        }
        /// <summary>
        /// Apply a filter to show only items matching the filter
        /// </summary>
        /// <param name="Filter">Filter value</param>
        public void FilterItems(string Filter)
        {
            Items.Clear();

            foreach (string Chan in Channels)
            {
                if (Chan.ToUpper().Contains(Filter.ToUpper()) || Filter.Equals(""))
                {
                    Items.Add(Chan, 0);
                }
            }
        }
Exemplo n.º 31
0
 public void GetBoard()
 {
     try
     {
         BoardRootObject board = Chan.GetBoard();
         Assert.NotNull(board);
     }
     catch (Exception e)
     {
         Assert.Fail(e.Message);
     }
 }
Exemplo n.º 32
0
        // worker thread
        void OnProxyConnected(Chan chan)
        {
            chan.recvHandler += HandleProxyRecv;
#if UNITY_EDITOR
            chan.recvHandler += OnStatProxyRecv;
            chan.onSend      += OnStatProxySend;
#endif
            TaskManager.PerformOnMainThread(
                (obj) =>
            {
                onProxyConnected.Invoke(chan);
            });
        }
Exemplo n.º 33
0
        /// <summary>
        /// Creates a channel which fires after the specified timeout.
        /// </summary>
        public static Chan<bool> After(TimeSpan timeout)
        {
            if (timeout < TimeSpan.Zero)
                throw new ArgumentOutOfRangeException("timeout", timeout, "timeout must be >= 0");

            var timeoutChan = new Chan<bool>();

            var started = DateTime.Now;

            System.Threading.Timer localTimer = null;
            System.Threading.Timer t = new System.Threading.Timer(
                delegate
                {
                    string threadName = string.Format("Time.After started:{0} duration:{1}", started, timeout);
                    Thread.CurrentThread.Name = threadName;
                    try
                    {
                        if (localTimer != null)
                        {
                            lock (_threadingTimersLocker)
                            {
                                _threadingTimers.Remove(localTimer);
                                localTimer.Dispose();
                                localTimer = null;
                            }
                        }
                    }
                    catch { }

                    try
                    {
                        if (!((IChan)timeoutChan).IsClosed)
                            timeoutChan.Send(default(bool));
                    }
                    catch { }

                }, null, timeout, TimeSpan.FromMilliseconds(-1));

            localTimer = t;

            lock (_threadingTimersLocker)
            {
                if (localTimer != null)
                {
                    _threadingTimers.Add(localTimer);
                }
            }

            return timeoutChan;
        }
Exemplo n.º 34
0
        public void Count()
        {
            var chan = new Chan<int>();

            chan
                .Send(Enumerable.Range(0, 10))
                .ContinueWith(t => chan.Close());

            var counting = chan.Count();

            if (!counting.Wait(TimeSpan.FromSeconds(10)))
            {
                Assert.Fail();
            }

            Assert.AreEqual(10, counting.Result);
        }
Exemplo n.º 35
0
        public void BufferedChannelsSelectReceiveInGoroutine()
        {
            var c = new Chan<int>(10);

            var list = new List<int>();
            var wg = new WaitGroup();

            wg.Add(1);

            GoFunc.Run(() =>
            {
                bool doLoop = true;
                while (doLoop)
                {
                    Select
                        .CaseReceiveOk(c, (i, ok) =>
                        {
                            if (ok)
                                list.Add(i);
                            else
                                doLoop = false;
                        })
                        .NoDefault();
                }

                wg.Done();
            }, "bufferChannelsTest:receiveLoop");

            for (int i = 0; i < 10; i++)
            {
                Select
                    .CaseSend(c, i)
                    .NoDefault();
            }

            c.Close();

            wg.Wait();

            Assert.AreEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, list.ToArray());
        }
Exemplo n.º 36
0
        public void AfterFired()
        {
            var c1 = Time.After(TimeSpan.FromMilliseconds(10));
            var c2 = new Chan<string>();

            var t1 = new Thread(() =>
                                {
                                    Thread.Sleep(200);
                                    c2.Send("no-timeout");
                                });
            t1.IsBackground = true;
            t1.Start();

            var list = new List<string>();

            Select
                .CaseReceive(c1, o => list.Add("timeout"))
                .CaseReceive(c2, list.Add)
                .NoDefault();

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual("timeout", list[0], "list[0]");
        }
Exemplo n.º 37
0
        public void CloseSelecting()
        {
            var msgChan = new Chan<int>();
            var closeChan = new Chan<bool>();

            Func<Task> select = async () =>
            {
                var run = true;

                while (run)
                {
                    await new Select()
                        .Case(msgChan, (_, ok) => {})
                        .Case(closeChan, (_, ok) => { run = false; })
                        .End();
                }
            };

            var t = select();

            msgChan.Close();
            closeChan.Send(true).ContinueWith(_ => t.Wait()).Wait();
        }
Exemplo n.º 38
0
        public void Forward()
        {
            var source = new Chan<int>();
            var target = new Chan<int>();

            var tasks =
                new Task[2];

            tasks[0] =
                source.Forward(target);

            source
                .Send(Enumerable.Range(0, 10))
                .ContinueWith(t => source.Close());

            var cnt = 0;
            tasks[1] =
                target.ForEach(item => cnt++);

            if (!Task.WaitAll(tasks, TimeSpan.FromSeconds(10)))
            {
                Assert.Fail();
            }
        }
Exemplo n.º 39
0
        public void Spread()
        {
            var chan1 = new Chan<int>();
            var chan2 = new Chan<int>();
            var chan3 = new Chan<int>();

            var source = new Chan<int>();

            var tasks = new Task[4];

            tasks[0] =
                source.Spread(new[] { chan1, chan2, chan3 });

            source
                .Send(Enumerable.Range(0, 10))
                .ContinueWith(t => source.Close());

            var cnt1 = 0;
            tasks[1] =
                chan1.ForEach(item => cnt1++);

            var cnt2 = 0;
            tasks[2] =
                chan2.ForEach(item => cnt2++);

            var cnt3 = 0;
            tasks[3] =
                chan3.ForEach(item => cnt3++);

            if (!Task.WaitAll(tasks, TimeSpan.FromSeconds(10)))
            {
                Assert.Fail();
            }

            Assert.AreEqual(30, cnt1 + cnt2 + cnt3);
        }
Exemplo n.º 40
0
        public void SelectTwoChannels()
        {
            var c1 = new Chan<int>();
            var c2 = new Chan<int>();

            var t1 = new Thread(() =>
                                {
                                    Thread.Sleep(10);
                                    c1.Send(1);
                                });
            t1.IsBackground = true;

            var t2 = new Thread(() => c2.Send(2));
            t2.IsBackground = true;

            var list = new List<int>();

            t2.Start();
            t1.Start();

            Select
                .CaseReceive(c1, list.Add)
                .CaseReceive(c2, list.Add)
                .NoDefault();

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual(2, list[0], "list[0]");
        }
Exemplo n.º 41
0
        public void SelectSendsOnly()
        {
            var c1 = new Chan<int>();
            var c2 = new Chan<int>();

            var t1 = new Thread(() =>
                                {
                                    Thread.Sleep(1000);
                                    c1.Receive();
                                });
            t1.IsBackground = true;

            var t2 = new Thread(() => c2.Receive());
            t2.IsBackground = true;

            var list = new List<int>();

            t1.Start();
            t2.Start();

            Select
                .CaseSend(c1, 1, () => list.Add(1))
                .CaseSend(c2, 2, () => list.Add(2))
                .NoDefault();

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual(2, list[0], "list[0]");
        }
Exemplo n.º 42
0
        public void Merge()
        {
            var chan1 = new Chan<int>();
            var chan2 = new Chan<int>();

            chan1
                .Send(Enumerable.Range(0, 10))
                .ContinueWith(t => chan1.Close());
            chan2
                .Send(Enumerable.Range(0, 10))
                .ContinueWith(t => chan2.Close());

            var mergedChan = chan1.Merge(chan2);

            var cnt = 0;
            var collection =
                mergedChan.ForEach(item => cnt++);

            if (!collection.Wait(TimeSpan.FromSeconds(10)))
            {
                Assert.Fail();
            }

            Assert.AreEqual(20, cnt);
        }
Exemplo n.º 43
0
        public void Select()
        {
            var chan = new Chan<int>();

            chan
                .Send(Enumerable.Range(0, 10))
                .ContinueWith(t => chan.Close());

            var sum = 0;
            var collection =
                chan
                    .Select(item => item % 2)
                    .ForEach(item => sum += item);

            if (!collection.Wait(TimeSpan.FromSeconds(10)))
            {
                Assert.Fail();
            }

            Assert.AreEqual(5, sum);
        }
Exemplo n.º 44
0
        public void SelectNotEmpty()
        {
            var closeChan = new Chan<bool>();

            closeChan.Send(true).Wait();

            Func<Task> select = async () =>
            {
                var run = true;

                while (run)
                {
                    await new Select()
                        .Case(closeChan, (_, ok) => { run = false; })
                        .End();
                }
            };

            select().Wait();
        }
Exemplo n.º 45
0
        public void TwoSelectsSendAndReceiveCanTalk()
        {
            var c = new Chan<int>();

            int actual = 0;

            var wg = new WaitGroup();
            wg.Add(2);

            GoFunc.Run(() =>
            {
                Select
                    .CaseSend(c, 7)
                    .NoDefault();

                wg.Done();
            });

            GoFunc.Run(() =>
            {
                Select
                    .CaseReceive(c, o => actual = o)
                    .NoDefault();

                wg.Done();
            });

            wg.Wait();

            Assert.AreEqual(7, actual);
        }
Exemplo n.º 46
0
        public void ReceiveOnClosedChannelReturnsDefault()
        {
            var c = new Chan<int>();
            c.Close();

            int val = c.Receive();
            Assert.AreEqual(default(int), val);
        }
Exemplo n.º 47
0
        public void PrimeSieve()
        {
            var generate = new Action<Chan<int>>(cgen =>
                           {
                               while (true)
                               {
                                   for (int i = 2; ; i++)
                                   {
                                       cgen.Send(i);
                                   }
                               }
                               // ReSharper disable once FunctionNeverReturns
                           });

            var filter = new Action<Chan<int>, Chan<int>, int>((cin, cout, prime) =>
                                                               {
                                                                   while (true)
                                                                   {
                                                                       var i = cin.Receive();
                                                                       if (i % prime != 0)
                                                                       {
                                                                           cout.Send(i);
                                                                       }
                                                                   }
                                                                   // ReSharper disable once FunctionNeverReturns
                                                               });

            var ch = new Chan<int>();

            Chan<int> generateCh = ch;
            var threadGenerate = new Thread(() => generate(generateCh));
            threadGenerate.IsBackground = true;
            threadGenerate.Start();

            var list = new List<int>();

            for (int i = 0; i < 10; i++)
            {
                int prime = ch.Receive();
                list.Add(prime);

                var ch0 = ch;
                var ch1 = new Chan<int>();

                var threadFilter = new Thread(() => filter(ch0, ch1, prime));
                threadFilter.IsBackground = true;
                threadFilter.Start();

                ch = ch1;
            }

            Assert.AreEqual(new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }, list);
        }
Exemplo n.º 48
0
        public void MultiThreadedSelectTestWithoutDefer()
        {
            var c1 = new Chan<int>();
            var c2 = new Chan<int>();
            var done = new Chan<bool>();
            var start = new Chan<bool>();

            int c1Count = 0;
            int c2Count = 0;

            int count = 0;
            int totalReceived = 0;

            Action receive = () =>
            {
                start.Receive();

                int val1 = 0;
                int val2 = 0;
                bool doLoop = true;

                while (doLoop)
                {
                    val1 = 0;
                    val2 = 0;

                    Select
                        .CaseReceive(c1, i => val1 = i)
                        .CaseReceive(c2, i => val2 = i)
                        .CaseReceive(done, b => doLoop = false)
                        .NoDefault();

                    if (doLoop)
                    {
                        Assert.IsTrue(val1 == 0 || val2 == 0, "val1 == 0 || val2 == 0");
                        Assert.IsTrue(val1 == 1 || val2 == 2, "val1 == 1 || val2 == 2");
                    }

                    Interlocked.Increment(ref totalReceived);
                }
            };

            Action send = () =>
            {
                start.Receive();

                while (count < 10000)
                {
                    Interlocked.Increment(ref count);

                    Select
                        .CaseSend(c1, 1, () => Interlocked.Increment(ref c1Count))
                        .CaseSend(c2, 2, () => Interlocked.Increment(ref c2Count))
                        .NoDefault();

                    Select
                        .CaseSend(c2, 2, () => Interlocked.Increment(ref c2Count))
                        .CaseSend(c1, 1, () => Interlocked.Increment(ref c1Count))
                        .NoDefault();
                }

                done.Close();
            };

            for (int i = 0; i < 8; i++)
            {
                GoFunc.Run(receive);
                GoFunc.Run(send);
            }

            start.Close();
            done.Receive();

            Assert.GreaterOrEqual(count, 10000);
            Assert.Greater(totalReceived, 19900);
        }
Exemplo n.º 49
0
        public void MultipleNumberGenerators()
        {
            var c = new Chan<int>();

            for (int i = 0; i < 10; i++)
            {
                int localNum = i;

                var t = new Thread(() => c.Send(localNum));
                t.IsBackground = true;
                t.Start();
            }

            var list = new List<int>();
            for (int i = 0; i < 10; i++)
            {
                list.Add(c.Receive());
            }

            list.Sort();

            Assert.AreEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, list);
        }
Exemplo n.º 50
0
        public void ClosedChannelsWithDataShouldNotReportClosedUntilDrained()
        {
            for (int i = 0; i < 10000; i++)
            {
                var chan = new Chan<int>();

                var wait = new AutoResetEvent(initialState: false);

                GoFunc.Run(() =>
                           {
                               chan.Send(1);
                               chan.Close();

                           }, "send");

                bool ok = false, ok2 = false;
                int actual = -1, actual2 = -1;

                GoFunc.Run(() =>
                           {
                               actual = chan.ReceiveOk(out ok);
                               actual2 = chan.ReceiveOk(out ok2);
                               wait.Set();
                           }, "receive");

                wait.WaitOne();

                Assert.AreEqual(true, ok, string.Format("ok iteration {0}", i));
                Assert.AreEqual(1, actual, string.Format("actual iteration {0}", i));
                Assert.AreEqual(false, ok2, string.Format("ok2 iteration {0}", i));
                Assert.AreEqual(default(int), actual2, string.Format("actual2 iteration {0}", i));
            }
        }
Exemplo n.º 51
0
        public void SendOnClosedChannelThrows()
        {
            var c = new Chan<int>();
            c.Close();

            Assert.Throws<ChannelClosedException>(() => c.Send(1));
        }
Exemplo n.º 52
0
        public void SelectDefaultCaseChannelReady()
        {
            var c1 = new Chan<int>();
            var c2 = new Chan<int>();

            var t1 = new Thread(() =>
            {
                Thread.Sleep(100);
                c1.Send(1);
            });
            t1.IsBackground = true;

            var t2 = new Thread(() => c2.Send(5));
            t2.IsBackground = true;

            var list = new List<int>();

            t1.Start();
            t2.Start();

            Thread.Sleep(50);

            Select
                .CaseReceive(c1, list.Add)
                .CaseReceive(c2, list.Add)
                .Default(() => list.Add(3));

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual(5, list[0], "list[0]");
        }
Exemplo n.º 53
0
        public void SingleNumberGeneratorIEnumerableChan()
        {
            var c = new Chan<int>();

            var t = new Thread(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    c.Send(i);
                }
                c.Close();
            });
            t.IsBackground = true;
            t.Start();

            var list = new List<int>();
            foreach (var i in (IEnumerable)c)
            {
                list.Add((int)i);
            }

            Assert.AreEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, list);
        }
Exemplo n.º 54
0
        public void SelectNullChannel()
        {
            var c1 = new Chan<int>();

            var t1 = new Thread(() =>
            {
                Thread.Sleep(10);
                c1.Send(3);
            });
            t1.IsBackground = true;

            var list = new List<int>();

            t1.Start();

            Select
                .CaseReceive((Chan<int>)null, list.Add)
                .CaseReceive(c1, list.Add)
                .NoDefault();

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual(3, list[0], "list[0]");
        }
Exemplo n.º 55
0
        public void SendReceive()
        {
            var chan = new Chan<int>();

            chan
                .Send(Enumerable.Range(0, 10))
                .ContinueWith(t => chan.Close());

            var cnt = 0;
            var collection =
                chan.ForEach(item => cnt++);

            if (!collection.Wait(TimeSpan.FromSeconds(10)))
            {
                Assert.Fail();
            }

            Assert.AreEqual(10, cnt);
        }
Exemplo n.º 56
0
        public void SelectSendAndReceiveReceiveReady()
        {
            object listLocker = new object();

            var c1 = new Chan<int>();
            var c2 = new Chan<int>();

            var t1 = new Thread(() =>
            {
                Thread.Sleep(150);
                c1.Send(1);
            });
            t1.IsBackground = true;

            var list = new List<int>();

            var t2 = new Thread(() =>
            {
                var val = c2.Receive();
                lock (listLocker)
                {
                    list.Add(val);
                }
            });
            t2.IsBackground = true;

            t1.Start();
            t2.Start();

            Select
                .CaseReceive(c1, func: o =>
                                       {
                                           lock (listLocker)
                                           {
                                               list.Add(o);
                                           }
                                       })
                .CaseSend(c2, message: 2)
                .NoDefault();

            Thread.Sleep(20);

            lock (listLocker)
            {
                Assert.AreEqual(1, list.Count, "list.Count");
                Assert.AreEqual(2, list[0], "list[0]");
            }
        }
Exemplo n.º 57
0
 public MockProducerConn(IConnDelegate connDelegate)
 {
     _connDelegate = connDelegate;
     _closeCh = new Chan<bool>();
     _pubCh = new Chan<bool>();
     GoFunc.Run(router, "ProducerTest:router");
 }
Exemplo n.º 58
0
        public void SelectSendAndReceiveSendReady()
        {
            var c1 = new Chan<int>();
            var c2 = new Chan<int>();

            var t1 = new Thread(() => c1.Send(1));
            t1.IsBackground = true;

            var list = new List<int>();

            var t2 = new Thread(() =>
                                {
                                    Thread.Sleep(50);
                                    list.Add(c2.Receive());
                                });
            t2.IsBackground = true;

            t1.Start();
            t2.Start();

            Select
                .CaseReceive(c1, list.Add)
                .CaseSend(c2, 2, () => { })
                .NoDefault();

            Assert.AreEqual(1, list.Count, "list.Count");
            Assert.AreEqual(1, list[0], "list[0]");
        }
Exemplo n.º 59
0
        public void BufferedChannelsSelectSendInGoroutine()
        {
            var c = new Chan<int>(10);

            var list = new List<int>();
            var wg = new WaitGroup();

            wg.Add(1);

            GoFunc.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Select
                        .CaseSend(c, i)
                        .NoDefault();
                }

                c.Close();
                wg.Done();
            }, "bufferedChannelsTest:sendLoop");

            wg.Wait();

            bool doLoop = true;
            // ReSharper disable once LoopVariableIsNeverChangedInsideLoop
            while (doLoop)
            {
                Select
                    .CaseReceiveOk(c, (i, ok) =>
                    {
                        if (ok)
                            list.Add(i);
                        else
                            doLoop = false;
                    })
                    .NoDefault();
            }

            Assert.AreEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, list.ToArray());
        }
Exemplo n.º 60
0
        /// <summary>
        ///     <para>Creates a new instance of <see cref="Consumer"/> for the specified <paramref name="topic"/> and
        ///     <paramref name="channel"/>, using the specified <paramref name="logger"/> and <paramref name="config"/>.</para>
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
        /// <exception cref="ArgumentException">Thrown when the <paramref name="topic"/> or
        ///     <paramref name="channel"/> exceed the maximum length or contain invalid characters. Topic and channel names
        ///     must be greater than 0 and less than or equal to 64 characters longer and must match the pattern "^[\.a-zA-Z0-
        ///     9_-]+(#ephemeral)?$".
        /// </exception>
        /// <param name="topic">The topic name.</param>
        /// <param name="channel">The channel name.</param>
        /// <param name="logger">The <see cref="ILogger"/> instance.</param>
        /// <param name="config">The <see cref="Config"/> settings. After config is passed in the values are no longer mutable
        ///     (they are copied).
        /// </param>
        public Consumer(string topic, string channel, ILogger logger, Config config)
        {
            if (string.IsNullOrEmpty(topic))
                throw new ArgumentNullException("topic");
            if (string.IsNullOrEmpty(channel))
                throw new ArgumentNullException("channel");
            if (config == null)
                throw new ArgumentNullException("config");
            if (logger == null)
                throw new ArgumentNullException("logger");

            config.Validate();

            if (!Protocol.IsValidTopicName(topic))
            {
                throw new ArgumentException("invalid topic name", "topic");
            }

            if (!Protocol.IsValidChannelName(channel))
            {
                throw new ArgumentException("invalid channel name", "channel");
            }

            _id = Interlocked.Increment(ref _instCount);

            _topic = topic;
            _channel = channel;
            _config = config.Clone();
            _logger = logger;

            _maxInFlight = config.MaxInFlight;

            _incomingMessages = new Chan<Message>();

            _rdyRetryTimers = new Dictionary<string, Timer>();
            _pendingConnections = new Dictionary<string, Conn>();
            _connections = new Dictionary<string, Conn>();

            _lookupdRecheckChan = new Chan<int>(bufferSize: 1);

            _rng = new RNGCryptoServiceProvider();

            _stopChan = new Chan<int>();
            _exitChan = new Chan<int>();

            _wg.Add(1);

            GoFunc.Run(rdyLoop, string.Format("rdyLoop: {0}/{1}", _topic, _channel));
        }