Ejemplo n.º 1
0
 private void AddToCache(ILogItem item)
 {
     semapore.Wait();
     try { _logCache.Add(item); }
     finally { semapore.Release(); }
     if (_logCache.Count >= _cacheMaxEntries)
     {
         SaveCache();
     }
 }
Ejemplo n.º 2
0
 private void Execute(Action method)
 {
     ss.Wait();
     try { method.Invoke(); }
     catch (Exception ex)
     {
         logger.FatalException(method.Method + " failed", ex); throw;
     }
     finally { ss.Release(); }
 }
Ejemplo n.º 3
0
        public void LiveObservableBaseListCollection([ValueSource("SchedulersToTest")] IScheduler scheduler)
        {
            var list = new List <int>
            {
                10,
                20
            };
            var baseList = list.AsListCollection();

            var  recievedValues = new List <int>();
            bool recievedError  = false;
            var  waitSem        = new System.Threading.SemaphoreSlim(0);

            var obs = baseList.ToObservable(ObservableType.LiveUpdating, scheduler);
            var dis = obs.Subscribe(x => recievedValues.Add(x), _ => recievedError = true, () => waitSem.Release());

            while (!waitSem.Wait(100))
            {
                ;
            }

            dis.Dispose();

            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10, 20 }));
            Assert.That(recievedError, Is.False);
        }
        private IEnumerable <PublicTrade> OnRecentTrades(Binance.WsTrade trade)
        {
            Debug.Print($"OnRecentTrades() : {System.Threading.Thread.CurrentThread.ManagedThreadId}");
            try
            {
                tradesLock.Wait();
                if (lastTradeId == 0)
                {
                    var trades = GetPublicTradesAsync(trade.symbol, TradesMaxItemCount).Result;
                    lastTradeId = trades.FirstOrDefault().Id;
                    return(trades);
                }
                else if (trade.tradeId > lastTradeId)
                {
                    var newTrade = Convert(trade);
                    lastTradeId = newTrade.Id;
                    return(Enumerable.Repeat(newTrade, 1));
                }
                else
                {
                    Debug.Print($"Trade {trade.tradeId} dropped");
                }

                return(Enumerable.Empty <PublicTrade>());
            }
            finally
            {
                tradesLock.Release();
            }
        }
Ejemplo n.º 5
0
        public void LiveObservableListInsertThreaded([ValueSource("SchedulersToTest")] IScheduler scheduler)
        {
            /* Test parts:
             * 1. observe values when insertion and observation occurs (at least from an API call perspective) at the same time
             * 2. observe values when insertion occurs after observation was started
             */

            var list = new List <int>
            {
                10,
                20
            };

            var obs = list.ToObservable(ObservableType.LiveUpdating, scheduler);

            var  recievedValues = new List <int>();
            bool recievedError  = false;

            void listInsert() => list.Insert(1, 30);

            void enumerateValues()
            {
                var waitSem = new System.Threading.SemaphoreSlim(0);

                var dis = obs.Subscribe(x => recievedValues.Add(x), _ => recievedError = true, () => waitSem.Release());

                while (!waitSem.Wait(100))
                {
                    ;
                }

                dis.Dispose();
            }

            // 1

            Parallel.Invoke
            (
                listInsert,
                enumerateValues
            );

            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10, 30, 20 }));
            Assert.That(recievedError, Is.False);

            // 2

            recievedValues.Clear();
            recievedError = false;

            list.RemoveAt(1);

            var enumerateTask = Task.Run((Action)enumerateValues);
            var insertTask    = Task.Delay(1).ContinueWith(_ => listInsert());

            Task.WaitAll(enumerateTask, insertTask);

            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10, 20 }));
            Assert.That(recievedError, Is.False);
        }
Ejemplo n.º 6
0
        public void InfiniteLiveObservableBaseListCollectionEmpty([ValueSource("SchedulersToTest")] IScheduler scheduler)
        {
            var list     = new List <int>();
            var baseList = list.AsListCollection();

            bool recievedValue = false;
            bool recievedError = false;
            bool completed     = false;
            var  waitSem       = new System.Threading.SemaphoreSlim(0);

            var obs  = baseList.ToObservable(ObservableType.InfiniteLiveUpdating, scheduler);
            var dis1 = obs.Subscribe(_ => recievedValue = true, _ => recievedError = true, () => completed = true);

            var dis2 = scheduler.Schedule(() =>
            {
                System.Threading.Thread.Sleep(50);
                waitSem.Release();
            });

            while (!waitSem.Wait(100))
            {
                ;
            }

            dis1.Dispose();
            dis2.Dispose();

            Assert.That(recievedValue, Is.False);
            Assert.That(recievedError, Is.False);
            Assert.That(completed, Is.False);
        }
Ejemplo n.º 7
0
 public ICssProcessor GetCss()
 {
     _semaphoreCss.Wait();
     if (poolCss.TryTake(out var res))
     {
         return(res);
     }
     return(new CssProcessor(_toolsDir));
 }
Ejemplo n.º 8
0
 public ITSCompiler GetTs()
 {
     _semaphore.Wait();
     if (pool.TryTake(out var res))
     {
         return(res);
     }
     return(new TsCompiler(_toolsDir, _logger));
 }
Ejemplo n.º 9
0
 public static void StdErrLog(string message, EventLogEntryType eventLogEntryType = EventLogEntryType.Information)
 {
     consoleErrorLock.Wait();
     try {
         System.Console.Error.WriteLine(GetConsoleLogString(message, eventLogEntryType));
     }
     finally {
         consoleErrorLock.Release();
     }
 }
Ejemplo n.º 10
0
 public ITSCompiler GetTs(DiskCache.IDiskCache diskCache, ITSCompilerOptions compilerOptions)
 {
     _semaphore.Wait();
     if (!_pool.TryTake(out var res))
     {
         res = new TsCompiler(_toolsDir, _logger);
     }
     res.DiskCache = diskCache;
     if (compilerOptions != null)
     {
         res.CompilerOptions = compilerOptions;
     }
     return(res);
 }
Ejemplo n.º 11
0
        private static void fileLog(string message, string entryType = "DEBUG")
        {
            if (CurrentLogLevel == LogLevel.Debug)
            {
                using (IsolatedStorageFile isoFile = GetIsolatedStorageFile()) {
                    logFileLock.Wait();
                    try {
                        //IsolatedStorage will be something like: C:\WINDOWS\system32\config\systemprofile\AppData\Local\IsolatedStorage\arpzpldm.neh\4hq14imw.y2b\Publisher.5yo4swcgiijiq5te00ddqtmrsgfhvrp4\AssemFiles\

                        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(ApplicationName + "_" + logStartTimestampString + ".log", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read, isoFile)) {
                            //stream.Seek(0, System.IO.SeekOrigin.End);

                            if (debugLogEventCount == 0)
                            {
                                try {
                                    LogFilePath = stream.GetType().GetField("m_FullPath", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(stream).ToString();
                                    if (logToEventLog && eventLogWriteEntryAction != null)
                                    {
                                        eventLogWriteEntryAction("Saving debug log to " + LogFilePath, EventLogEntryType.Information);
                                    }
                                    else
                                    {
                                        ConsoleLog("Saving debug log to " + LogFilePath);
                                    }
                                }
                                catch { }
                            }
                            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream)) {
                                writer.WriteLine(DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) + "\t[" + entryType + "]\t" + message);
                            }
                        }
                    }
                    catch (System.IO.IOException e) {
                        if (debugLogEventCount == 0 && eventLogWriteEntryAction != null)
                        {
                            eventLogWriteEntryAction(e.Message, EventLogEntryType.Error);
                        }
                    }
                    catch (System.NullReferenceException) {
                        LogToFile = false;
                    }
                    finally {
                        logFileLock.Release();
                        System.Threading.Interlocked.Increment(ref debugLogEventCount);
                    }
                }
            }
        }
Ejemplo n.º 12
0
        private static void Main(string[] args)
        {
            foreach (var i in Enumerable.Range(1, 10))
            {
                Task.Factory.StartNew(() =>
                {
                    Console.WriteLine($"Starting Task {Task.CurrentId}");
                    SemaphoreSlim.Wait();
                    Console.WriteLine($" - Completed Task {Task.CurrentId}");
                });
            }

            while (SemaphoreSlim.CurrentCount <= 2)
            {
                Console.WriteLine($"Current Count {SemaphoreSlim.CurrentCount}");
                Console.ReadKey();
                SemaphoreSlim.Release(2);
            }
        }
        private IEnumerable <OrderBookEntry> OnOrderBook3(Binance.WsDepth depth)
        {
            Debug.Print($"OnOrderBook3() : {System.Threading.Thread.CurrentThread.ManagedThreadId}");
            try
            {
                _lock.Wait();
                if (OrderBook.lastUpdateId == 0)
                {
                    var result = client.GetDepthAsync(depth.symbol, OrderBookMaxItemCount).Result;
                    if (result.Success)
                    {
                        var tmp = Convert(result.Data, OrderBook.SymbolInformation);
                        OrderBook.lastUpdateId = result.Data.lastUpdateId;
                        return(tmp);
                        //Debug.Print($"{lastUpdateId}");
                    }
                }
                if (depth.finalUpdateId <= OrderBook.lastUpdateId)
                {
                    Debug.Print($"{depth.firstUpdateId} : {depth.finalUpdateId}  dropped");
                }
                else if (depth.firstUpdateId <= OrderBook.lastUpdateId + 1 && depth.finalUpdateId >= OrderBook.lastUpdateId + 1)
                {
                    var sw          = Stopwatch.StartNew();
                    var bookUpdates = Convert(depth, OrderBook.SymbolInformation);

                    OrderBook.lastUpdateId = depth.finalUpdateId;
                    Debug.Print($"Update {OrderBook.lastUpdateId} took {sw.ElapsedMilliseconds}ms.");

                    return(bookUpdates);
                }
                else
                {
                    Debug.Print($"{depth.firstUpdateId} : {depth.finalUpdateId}  dropped");
                }
                return(Enumerable.Empty <OrderBookEntry>());
            }
            finally
            {
                _lock.Release();
            }
        }
Ejemplo n.º 14
0
        public void InfiniteLiveObservableBaseListCollectionPostAddition([ValueSource("SchedulersToTest")] IScheduler scheduler)
        {
            var list     = new List <int>();
            var baseList = list.AsListCollection();

            var obs = baseList.ToObservable(ObservableType.InfiniteLiveUpdating, scheduler);

            var  recievedValues = new List <int>();
            bool recievedError  = false;
            bool completed      = false;
            var  waitSem        = new System.Threading.SemaphoreSlim(0);

            var addedTime = DateTime.Now.AddSeconds(1);

            void onValue(int x)
            {
                addedTime = DateTime.Now;
                recievedValues.Add(x);
                waitSem.Release();
            }

            var dis = obs.Subscribe(onValue, _ => recievedError = true, () => completed = true);

            var insertTime = DateTime.Now;

            baseList.Add(10);

            while (!waitSem.Wait(10))
            {
                ;
            }

            dis.Dispose();

            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10 }));
            Assert.That(recievedError, Is.False);
            Assert.That(completed, Is.False);
            Assert.That(addedTime, Is.EqualTo(insertTime).Within(125).Milliseconds);
        }
Ejemplo n.º 15
0
        public void InfiniteLiveObservableList([ValueSource("SchedulersToTest")] IScheduler scheduler)
        {
            var list = new List <int>
            {
                10,
                20
            };

            var  recievedValues = new List <int>();
            bool recievedError  = false;
            bool completed      = false;
            var  waitSem        = new System.Threading.SemaphoreSlim(0);

            var obs  = list.ToObservable(ObservableType.InfiniteLiveUpdating, scheduler);
            var dis1 = obs.Subscribe(x => recievedValues.Add(x), _ => recievedError = true, () => completed = true);

            var dis2 = scheduler.Schedule(() =>
            {
                if (recievedValues.Count != 2)
                {
                    System.Threading.Thread.Sleep(50);
                }
                waitSem.Release();
            });

            while (!waitSem.Wait(100))
            {
                ;
            }

            dis1.Dispose();
            dis2.Dispose();

            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10, 20 }));
            Assert.That(recievedError, Is.False);
            Assert.That(completed, Is.False);
        }
Ejemplo n.º 16
0
        private ExpressionStringComparision ListStorageTest <T>(IQbservable <T> queryToTest, IScheduler scheduler, out int count, out int nonNullIndex)
        {
            var schedulerName = GetSchedulerName(scheduler);

            var waitSem = new System.Threading.SemaphoreSlim(0);

            int counter = 0;
            int nonNull = -1;
            var result  = CompareExpressionsTest(queryToTest, (query, timer) =>
            {
                IDisposable disposable;
                using (timer.NewContext(schedulerName))
                {
                    disposable = query.Subscribe(en =>
                    {
                        if (en != null)
                        {
                            nonNull = counter;
                        }

                        counter++;
                    }, () => waitSem.Release());
                }

                while (!waitSem.Wait(10))
                {
                    ;
                }

                disposable.Dispose();
            });

            count        = counter;
            nonNullIndex = nonNull;

            return(result);
        }
Ejemplo n.º 17
0
        public void InfiniteLiveObservableBaseListCollectionInsert([ValueSource("SchedulersToTest")] IScheduler scheduler)
        {
            /* Test parts:
             * 1. observe values (observable is still running)
             * 2. insert value (observable is terminated) and ensure it was not observed (since it would be before the current "iteration index")
             * 3. new observe values (observable is terminated) but this one should have the inserted value as it's a new iteration index and the value came after the new iteration index
             */

            // 1

            var list = new List <int>
            {
                10,
                20
            };
            var baseList = list.AsListCollection();

            var  recievedValues = new List <int>();
            bool recievedError  = false;
            bool completed      = false;
            var  waitSem        = new System.Threading.SemaphoreSlim(0);

            var obs  = baseList.ToObservable(ObservableType.InfiniteLiveUpdating, scheduler);
            var dis1 = obs.Subscribe(x => recievedValues.Add(x), _ => recievedError = true, () => completed = true);

            var dis2 = scheduler.Schedule(() =>
            {
                if (recievedValues.Count != 2)
                {
                    System.Threading.Thread.Sleep(50);
                }
                waitSem.Release();
            });

            while (!waitSem.Wait(100))
            {
                ;
            }

            dis2.Dispose();

            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10, 20 }));
            Assert.That(recievedError, Is.False);
            Assert.That(completed, Is.False);

            // 2

            list.Insert(1, 30);

            dis2 = scheduler.Schedule(() =>
            {
                if (recievedValues.Count != 2)
                {
                    System.Threading.Thread.Sleep(50);
                }
                waitSem.Release();
            });

            while (!waitSem.Wait(100))
            {
                ;
            }

            dis1.Dispose();
            dis2.Dispose();

            // Difference between this and the finite one
            // - finite one will have finished and a new subscription is needed to get the inserted value
            // - infinite one will still be running and will get the notification of the inserted item. But the insertion will be past where the index is, so it will notify of it.
            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10, 20 }));
            Assert.That(recievedError, Is.False);
            Assert.That(completed, Is.False);

            // 3

            recievedValues.Clear();
            recievedError = false;
            completed     = false;

            dis1 = obs.Subscribe(x => recievedValues.Add(x), _ => recievedError = true, () => completed = true);
            dis2 = scheduler.Schedule(() =>
            {
                if (recievedValues.Count != 3)
                {
                    System.Threading.Thread.Sleep(50);
                }
                waitSem.Release();
            });

            while (!waitSem.Wait(100))
            {
                ;
            }

            dis1.Dispose();
            dis2.Dispose();

            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10, 30, 20 }));
            Assert.That(recievedError, Is.False);
            Assert.That(completed, Is.False);
        }
Ejemplo n.º 18
0
        public static void RunWithController(TestHelper helper, IControllerPrx controller)
        {
            Communicator?communicator = helper.Communicator();

            TestHelper.Assert(communicator != null);

            var timeout = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), communicator);

            System.IO.TextWriter output = helper.GetWriter();
            output.Write("testing connect timeout... ");
            output.Flush();
            {
                Dictionary <string, string>?properties = communicator.GetProperties();
                properties["Ice.ConnectTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                // Expect ConnectTimeoutException.
                controller.HoldAdapter(-1);
                try
                {
                    to.Op();
                    TestHelper.Assert(false);
                }
                catch (ConnectTimeoutException)
                {
                    // Expected.
                }
                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            {
                //
                // Expect success.
                //
                controller.HoldAdapter(100);
                timeout.Op();
            }
            output.WriteLine("ok");

            // The sequence needs to be large enough to fill the write/recv buffers
            byte[] seq = new byte[2000000];

            output.Write("testing connection timeout... ");
            output.Flush();
            {
                //
                // Expect TimeoutException.
                //
                controller.HoldAdapter(-1);
                timeout.GetConnection() !.Acm = new Acm(TimeSpan.FromMilliseconds(50),
                                                        AcmClose.OnInvocationAndIdle,
                                                        AcmHeartbeat.Off);
                try
                {
                    timeout.SendData(seq);
                    TestHelper.Assert(false);
                }
                catch (ConnectionTimeoutException)
                {
                    // Expected.
                }
                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            {
                //
                // Expect success.
                //
                controller.HoldAdapter(100);
                try
                {
                    timeout.SendData(new byte[1000000]);
                }
                catch (ConnectionTimeoutException)
                {
                    TestHelper.Assert(false);
                }
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeout... ");
            output.Flush();
            {
                timeout.IcePing(); // Makes sure a working connection is associated with the proxy
                Connection? connection = timeout.GetConnection();
                ITimeoutPrx?to         = timeout.Clone(invocationTimeout: 100);
                TestHelper.Assert(connection == to.GetConnection());
                try
                {
                    to.Sleep(1000);
                    TestHelper.Assert(false);
                }
                catch (TimeoutException)
                {
                }
                timeout.IcePing();
                to = timeout.Clone(invocationTimeout: 1000);
                TestHelper.Assert(connection == to.GetConnection());
                try
                {
                    to.Sleep(100);
                }
                catch (TimeoutException)
                {
                    TestHelper.Assert(false);
                }
                TestHelper.Assert(connection == to.GetConnection());
            }
            {
                //
                // Expect TimeoutException.
                //
                ITimeoutPrx to = timeout.Clone(invocationTimeout: 100);
                try
                {
                    to.SleepAsync(1000).Wait();
                }
                catch (AggregateException ex) when(ex.InnerException is TimeoutException)
                {
                }
                timeout.IcePing();
            }
            {
                // Expect success.
                ITimeoutPrx to = timeout.Clone(invocationTimeout: 1000);
                to.SleepAsync(100).Wait();
            }

            output.WriteLine("ok");

            output.Write("testing close timeout... ");
            output.Flush();
            {
                Dictionary <string, string> properties = communicator.GetProperties();
                properties["Ice.CloseTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                Connection?connection  = to.GetConnection();
                Connection?connection2 = timeout.GetConnection();  // No close timeout

                TestHelper.Assert(connection != null && connection2 != null);

                controller.HoldAdapter(-1);

                // Make sure there's no ReadAsync pending
                _ = to.IcePingAsync();
                _ = timeout.IcePingAsync();

                var semaphore = new System.Threading.SemaphoreSlim(0);
                connection.Closed += (sender, args) => semaphore.Release();
                connection.Close(ConnectionClose.Gracefully);
                TestHelper.Assert(semaphore.Wait(500));

                connection2.Closed += (sender, args) => semaphore.Release();
                connection2.Close(ConnectionClose.Gracefully);
                TestHelper.Assert(!semaphore.Wait(500));

                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeouts with collocated calls... ");
            output.Flush();
            {
                communicator.SetProperty("TimeoutCollocated.AdapterId", "timeoutAdapter");

                ObjectAdapter adapter = communicator.CreateObjectAdapter("TimeoutCollocated");
                adapter.Activate();

                ITimeoutPrx proxy =
                    adapter.AddWithUUID(new Timeout(), ITimeoutPrx.Factory).Clone(invocationTimeout: 100);
                try
                {
                    proxy.Sleep(500);
                    TestHelper.Assert(false);
                }
                catch (TimeoutException)
                {
                }

                try
                {
                    proxy.SleepAsync(500).Wait();
                    TestHelper.Assert(false);
                }
                catch (AggregateException ex) when(ex.InnerException is TimeoutException)
                {
                }
                adapter.Dispose();
            }
            output.WriteLine("ok");

            controller.Shutdown();
        }
 public void Wait()
 {
     _semaphore.Wait();
     Interlocked.Increment(ref _currentRequests);
 }
Ejemplo n.º 20
0
        public static void RunWithController(TestHelper helper, IControllerPrx controller)
        {
            Communicator?communicator = helper.Communicator;

            TestHelper.Assert(communicator != null);
            bool ice1 = TestHelper.GetTestProtocol(communicator.GetProperties()) == Protocol.Ice1;

            var timeout = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), communicator);

            System.IO.TextWriter output = helper.Output;
            output.Write("testing connect timeout... ");
            output.Flush();
            {
                Dictionary <string, string>?properties = communicator.GetProperties();
                properties["Ice.ConnectTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                // Expect ConnectTimeoutException.
                controller.HoldAdapter(-1);
                try
                {
                    to.Op();
                    TestHelper.Assert(false);
                }
                catch (ConnectTimeoutException)
                {
                    // Expected.
                }
                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            {
                // Expect success.
                controller.HoldAdapter(100);
                timeout.Op();
            }
            output.WriteLine("ok");

            // The sequence needs to be large enough to fill the write/recv buffers
            byte[] seq = new byte[2000000];

            output.Write("testing connection timeout... ");
            output.Flush();
            {
                // Expect TimeoutException.
                controller.HoldAdapter(-1);
                timeout.GetConnection().Acm = new Acm(TimeSpan.FromMilliseconds(50),
                                                      AcmClose.OnInvocationAndIdle,
                                                      AcmHeartbeat.Off);
                try
                {
                    timeout.SendData(seq);
                    TestHelper.Assert(false);
                }
                catch (ConnectionClosedException)
                {
                    // Expected.
                }
                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            {
                // Expect success.
                controller.HoldAdapter(100);
                try
                {
                    timeout.SendData(new byte[1000000]);
                }
                catch (ConnectionClosedException)
                {
                    TestHelper.Assert(false);
                }
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeout... ");
            output.Flush();
            {
                timeout.IcePing(); // Makes sure a working connection is associated with the proxy
                Connection?connection = timeout.GetConnection();
                try
                {
                    timeout.Clone(invocationTimeout: TimeSpan.FromMilliseconds(100)).SleepAsync(1000).Wait();
                    TestHelper.Assert(false);
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                }
                timeout.IcePing();

                TestHelper.Assert(connection == timeout.GetConnection());
                try
                {
                    timeout.Clone(invocationTimeout: TimeSpan.FromMilliseconds(1000)).SleepAsync(100).Wait();
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                    TestHelper.Assert(false);
                }
                TestHelper.Assert(connection == timeout.GetConnection());
            }
            output.WriteLine("ok");

            output.Write("testing close timeout... ");
            output.Flush();
            {
                Dictionary <string, string> properties = communicator.GetProperties();
                properties["Ice.CloseTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                Connection?connection  = to.GetConnection();
                Connection?connection2 = timeout.GetConnection();  // No close timeout

                TestHelper.Assert(connection != null && connection2 != null);

                controller.HoldAdapter(-1);

                // Make sure there's no ReadAsync pending
                _ = to.IcePingAsync();
                _ = timeout.IcePingAsync();

                var semaphore = new System.Threading.SemaphoreSlim(0);
                connection.Closed += (sender, args) => semaphore.Release();
                connection.GoAwayAsync();
                TestHelper.Assert(semaphore.Wait(500));

                connection2.Closed += (sender, args) => semaphore.Release();
                connection2.GoAwayAsync();
                TestHelper.Assert(!semaphore.Wait(500));

                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeouts with collocated calls... ");
            output.Flush();
            {
                communicator.SetProperty("TimeoutCollocated.AdapterId", "timeoutAdapter");

                ObjectAdapter adapter = communicator.CreateObjectAdapter("TimeoutCollocated");
                adapter.Activate();

                ITimeoutPrx proxy = adapter.AddWithUUID(new Timeout(), ITimeoutPrx.Factory);
                try
                {
                    proxy.Clone(invocationTimeout: TimeSpan.FromMilliseconds(100)).SleepAsync(500).Wait();
                    TestHelper.Assert(false);
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                }

                adapter.Dispose();
            }
            output.WriteLine("ok");

            if (!ice1)
            {
                output.Write("testing deadlines... ");
                output.Flush();
                {
                    var comm1 = new Communicator(
                        communicator.GetProperties(),
                        invocationInterceptors: new InvocationInterceptor[]
                    {
                        (target, request, next, cancel) =>
                        {
                            request.AddBinaryContextEntry(10, request.Deadline, (ostr, value) =>
                            {
                                var deadline = (value - DateTime.UnixEpoch).TotalMilliseconds;
                                ostr.WriteVarLong((long)deadline);
                            });
                            return(next(target, request, cancel));
                        }
                    });

                    for (int i = 1000; i < 5000;)
                    {
                        i += 33;
                        ITimeoutPrx to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm1).Clone(
                            invocationTimeout: TimeSpan.FromMilliseconds(i));
                        TestHelper.Assert(to.CheckDeadline());
                    }
                }
                output.WriteLine("ok");
            }
            controller.Shutdown();
        }
Ejemplo n.º 21
0
        public void InfiniteLiveObservableBaseListCollectionInsertThreaded([ValueSource("SchedulersToTest")] IScheduler scheduler)
        {
            /* Test parts:
             * 1. observe values when insertion and observation occurs (at least from an API call perspective) at the same time
             * 2. observe values when insertion occurs after observation was started
             */

            var list = new List <int>
            {
                10,
                20
            };
            var baseList = list.AsListCollection();

            var obs = baseList.ToObservable(ObservableType.InfiniteLiveUpdating, scheduler);

            var  recievedValues = new List <int>();
            bool recievedError  = false;
            bool completed      = false;
            var  waitSem        = new System.Threading.SemaphoreSlim(0);

            void listInsert() => baseList.Insert(1, 30);
            Action enumerateValues(int expectedCount) => new Action(() =>
            {
                var dis1 = obs.Subscribe(x => recievedValues.Add(x), _ => recievedError = true, () => completed = true);
                var dis2 = scheduler.Schedule(() =>
                {
                    if (recievedValues.Count != expectedCount)
                    {
                        System.Threading.Thread.Sleep(50);
                    }
                    waitSem.Release();
                });

                while (!waitSem.Wait(100))
                {
                    ;
                }

                dis1.Dispose();
                dis2.Dispose();
            });

            // 1

            Parallel.Invoke
            (
                listInsert,
                enumerateValues(3)
            );

            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10, 30, 20 }));
            Assert.That(recievedError, Is.False);
            Assert.That(completed, Is.False);

            // 2

            recievedValues.Clear();
            recievedError = false;
            completed     = false;

            list.RemoveAt(1);

            var enumerateTask = Task.Run(enumerateValues(2));
            var insertTask    = Task.Delay(1).ContinueWith(_ => listInsert());

            Task.WaitAll(enumerateTask, insertTask);

            Assert.That(recievedValues, Is.EquivalentTo(new int[] { 10, 20 }));
            Assert.That(recievedError, Is.False);
            Assert.That(completed, Is.False);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// タイマイベント
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void TimerCapFlame(object sender)
        {
            //複数スレッドでの同時実行を抑制
            if (!semaphore.Wait(0))
            {
                return;
            }
            else if (this.ModelGen == null)
            {
                semaphore.Release();
                return;
            }

            try
            {
                //AIモデルのインプットデータは解像度224x224,BGRA8にする必要がある。
                BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Bgra8;
                using (VideoFrame previewFrame = new VideoFrame(InputPixelFormat, 640, 480, BitmapAlphaMode.Ignore))
                {
                    //フレームを取得
                    await this.mediaCapture.GetPreviewFrameAsync(previewFrame);

                    if (previewFrame != null)                           //フレームを正しく取得できた時
                    {
                        //モデルへのデータ入力クラスでインスタンスを作成する
                        var modelInput = new Input();

                        //SoftwareBitmapを作成
                        SoftwareBitmap bitmapBuffer = new SoftwareBitmap(BitmapPixelFormat.Bgra8, 224, 224, BitmapAlphaMode.Ignore);

                        //SoftwareBitmapでVideoFrameを作成する
                        VideoFrame buffer = VideoFrame.CreateWithSoftwareBitmap(bitmapBuffer);

                        //キャプチャしたフレームを作成したVideoFrameへコピーする
                        await previewFrame.CopyToAsync(buffer);

                        //SoftwareBitmapを取得する(これはリサイズ済みになる)
                        SoftwareBitmap resizedBitmap = buffer.SoftwareBitmap;

                        //WritableBitmapへ変換する
                        WriteableBitmap innerBitmap = null;
                        byte[]          buf         = null;
                        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => {
                            innerBitmap = new WriteableBitmap(resizedBitmap.PixelWidth, resizedBitmap.PixelHeight);

                            resizedBitmap.CopyToBuffer(innerBitmap.PixelBuffer);
                            buf = new byte[innerBitmap.PixelBuffer.Length];
                            innerBitmap.PixelBuffer.CopyTo(buf);
                        });

                        //バッファへコピーする
                        //innerBitmap.PixelBuffer.CopyTo(buf);6
                        SoftwareBitmap sb = SoftwareBitmap.CreateCopyFromBuffer(buf.AsBuffer(), BitmapPixelFormat.Bgra8, 224, 224, BitmapAlphaMode.Ignore);

                        //取得画像をコントロールに表示する
                        await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                        {
                            var src = new SoftwareBitmapSource();
                            //await src.SetBitmapAsync(previewFrame.SoftwareBitmap);
                            await src.SetBitmapAsync(sb);
                            Image_CapImg.Source = src;
                        });

                        //画像のアルファチャンネル削除と配列形状変更
                        byte[] buf2 = ConvertImageaArray(buf);


                        //正規化しつつfloat配列に変換する
                        float[] inData = NormalizeImage(buf2);

                        //入力用のテンソルを作成(Windows.AI.MachineLearning.TensorFloatクラス)
                        TensorFloat tf =
                            TensorFloat.CreateFromArray(new long[] { 1, 3, 224, 224 }, inData);

                        //入力フォーマットに合わせたデータをセットする
                        Input indata = new Input();
                        indata.data     = tf;
                        modelInput.data = tf;

                        //AIモデルにデータを渡すと推定値の入ったリストが返る
                        //ModelOutput = await ModelGen.EvaluateAsync(modelInput);
                        var output = await ModelGen.EvaluateAsync(modelInput);

                        //UIスレッドに結果を表示
                        await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            //予測結果を表示
                            //string label = outputData.classLabel[0];
                            var result_vec = output.mobilenetv20_output_flatten0_reshape0.GetAsVectorView();
                            var list       = result_vec.ToArray <float>();
                            var max1st     = list.Max();
                            var index1st   = Array.IndexOf(list, max1st);                               //最大確立のインデックスを取得

                            string ans = classList.Classes[index1st].ToString();
                            //result = result + "Class: " + label + ", Prob: " + ModelOutput.prob_1[label];

                            //結果表示
                            this.Text_Result_1st.Text = ans + ":" + max1st.ToString("0.0");
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("周期処理で例外発生");
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                semaphore.Release();
            }
        }
Ejemplo n.º 23
0
        public static async Task RunWithControllerAsync(TestHelper helper, IControllerPrx controller)
        {
            Communicator communicator = helper.Communicator;

            bool ice1 = TestHelper.GetTestProtocol(communicator.GetProperties()) == Protocol.Ice1;

            var timeout = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), communicator);

            System.IO.TextWriter output = helper.Output;
            output.Write("testing connect timeout... ");
            output.Flush();
            {
                Dictionary <string, string> properties = communicator.GetProperties();
                properties["Ice.ConnectTimeout"] = "100ms";
                await using var comm             = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                // Expect ConnectTimeoutException.
                controller.HoldAdapter(-1);
                try
                {
                    to.Op();
                    TestHelper.Assert(false);
                }
                catch (ConnectTimeoutException)
                {
                    // Expected.
                }
                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            {
                // Expect success.
                controller.HoldAdapter(100);
                timeout.Op();
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeout... ");
            output.Flush();
            {
                timeout.IcePing(); // Makes sure a working connection is associated with the proxy
                Connection connection = await timeout.GetConnectionAsync();

                try
                {
                    timeout.Clone(invocationTimeout: TimeSpan.FromMilliseconds(100)).SleepAsync(1000).Wait();
                    TestHelper.Assert(false);
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                }
                timeout.IcePing();

                TestHelper.Assert(connection == await timeout.GetConnectionAsync());
                try
                {
                    timeout.Clone(invocationTimeout: TimeSpan.FromMilliseconds(1000)).SleepAsync(100).Wait();
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                    TestHelper.Assert(false);
                }
                TestHelper.Assert(connection == await timeout.GetConnectionAsync());

                try
                {
                    timeout.Clone(invocationTimeout: TimeSpan.FromMilliseconds(100)).Sleep(1000);
                    TestHelper.Assert(false);
                }
                catch (OperationCanceledException)
                {
                }
            }
            output.WriteLine("ok");

            output.Write("testing close timeout... ");
            output.Flush();
            {
                Dictionary <string, string> properties = communicator.GetProperties();
                properties["Ice.CloseTimeout"] = "100ms";
                await using var comm           = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                Connection connection = await to.GetConnectionAsync();

                Connection connection2 = await timeout.GetConnectionAsync(); // No close timeout

                TestHelper.Assert(connection != null && connection2 != null);

                controller.HoldAdapter(-1);

                // Make sure there's no ReadAsync pending
                _ = to.IcePingAsync();
                _ = timeout.IcePingAsync();

                var semaphore = new System.Threading.SemaphoreSlim(0);
                connection.Closed += (sender, args) => semaphore.Release();
                _ = connection.GoAwayAsync();
                TestHelper.Assert(semaphore.Wait(500));

                connection2.Closed += (sender, args) => semaphore.Release();
                _ = connection2.GoAwayAsync();
                TestHelper.Assert(!semaphore.Wait(500));

                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            output.WriteLine("ok");

            if (!ice1)
            {
                output.Write("testing deadlines... ");
                output.Flush();
                {
                    var comm1 = new Communicator(communicator.GetProperties());

                    comm1.DefaultInvocationInterceptors = ImmutableList.Create <InvocationInterceptor>(
                        (target, request, next, cancel) =>
                    {
                        request.BinaryContextOverride.Add(10, ostr =>
                        {
                            var deadline = (request.Deadline - DateTime.UnixEpoch).TotalMilliseconds;
                            ostr.WriteVarLong((long)deadline);
                        });
                        return(next(target, request, cancel));
                    });

                    for (int i = 1000; i < 5000;)
                    {
                        i += 33;
                        ITimeoutPrx to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm1).Clone(
                            invocationTimeout: TimeSpan.FromMilliseconds(i));
                        TestHelper.Assert(to.CheckDeadline());
                    }
                }
                output.WriteLine("ok");
            }
            controller.Shutdown();
        }
Ejemplo n.º 24
0
 public void Wait()
 {
     _semaphore.Wait();
 }