Example #1
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);
        }
Example #2
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);
        }
        public static Task ConcurrentConnectService <T>(IEnumerable <T> sourse, Func <T, Task> f, int max)
        {
            var initial = (max >> 1);
            var s       = new System.Threading.SemaphoreSlim(initial, max);

            _ = Task.Run(async() => {
                for (int i = initial; i < max; i++)
                {
                    await Task.Delay(100);
                    s.Release();
                }
            });
            return(Task.WhenAll(from item in sourse
                                select Task.Run(async() =>
            {
                await s.WaitAsync();
                try
                {
                    await f(item);
                }
                finally
                {
                    s.Release();
                }
            })));
        }
Example #4
0
 public CompilerPool(IToolsDir toolsDir, ILogger logger, int parallelCompilations = 1)
 {
     _toolsDir     = toolsDir;
     _logger       = logger;
     _semaphore    = new System.Threading.SemaphoreSlim(parallelCompilations);
     _semaphoreCss = new System.Threading.SemaphoreSlim(parallelCompilations);
 }
Example #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);
        }
Example #6
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public GertbotUartController()
 {
     this.semaphore = new System.Threading.SemaphoreSlim(
         1, // Initial count > 0: the semaphore is initially free
         1  // Max count: only one thread can enter at a time
         );
 }
Example #7
0
 internal virtual void SetReadOnly(bool makeReadOnly)
 {
     this.ThrowIfDisposed();
     if (makeReadOnly == isReadOnly)
         return;
     readOnlySemaphore = !makeReadOnly ? null : new System.Threading.SemaphoreSlim(1);
     isReadOnly = makeReadOnly;
 }
Example #8
0
        public Timers(double updateInterval, TeamoEntry entry, TeamoContext context, IClientService clientService, ILogger logger)
        {
            _context       = context;
            _clientService = clientService;
            _entry         = entry;
            _logger        = logger;

            _semaphore = new System.Threading.SemaphoreSlim(1, 1);
            bool isUpdating = false;
            var  entryId    = _entry.Id.Value;

            // Update timer
            _updateTimer = new Timer
            {
                Interval  = updateInterval,
                AutoReset = true
            };
            _updateTimer.Elapsed += async(sender, e) =>
            {
                if (isUpdating)
                {
                    return;
                }
                Console.WriteLine($"[TIMER] Updating {entryId}");
                await ExclusiveAsync(async() =>
                {
                    var dbEntry = _context.GetEntry(entryId);
                    await _clientService.UpdateMessageAsync(dbEntry);
                });

                Console.WriteLine($"[TIMER] Update done {entryId}");
            };


            // Start timer
            _startTimer = new Timer
            {
                AutoReset = false
            };
            _startTimer.Elapsed += async(sender, e) =>
            {
                Console.WriteLine($"[TIMER] Starting finish {entryId}");
                _updateTimer.Stop();
                await ExclusiveAsync(async() =>
                {
                    _logger.LogInformation($"Creating start message for entry {entryId}");
                    var dbEntry = _context.GetEntry(entryId);
                    await _clientService.DeleteMessageAsync(entry.Message);
                    await _clientService.CreateStartMessageAsync(dbEntry);
                    await _context.DeleteAsync(entry.Id.Value);
                    EventHandler <ElapsedEventArgs> handler = TimerFinished;
                    handler?.Invoke(sender, e);
                    _logger.LogInformation($"Successfully created start message for {entryId}");
                });

                Console.WriteLine($"[TIMER] Finished {entryId}");
            };
        }
Example #9
0
        public WebServer()
        {
            _thumbnailsSemaphore = new System.Threading.SemaphoreSlim(4, 4);
            _listener            = new HttpListener();
            Engine = new Engine()
            {
                LocalSettings = ORB4.Engine.Settings.Load()
            };
            BeatmapDownloader = new BeatmapDownloader(ref Engine);

            Token = Guid.NewGuid().ToByteArray();

            Logger.MainLogger.Log(Logger.LogTypes.Info, "BrowserObject.RegisterJS -> Success");

            Url = $"http://localhost:{GetAvailablePort(41500)}/";

            _listener.Prefixes.Add(Url);

            _resources = new Dictionary <string, HtmlResource>()
            {
                { "/html/mainwindow.html", new HtmlResource(0, "text/html") },
                { "/html/settings.html", new HtmlResource(1, "text/html") },
                { "/css/main.css", new HtmlResource(2, "text/css") },
                { "/css/night.css", new HtmlResource(17, "text/css") },
                { "/css/default.css", new HtmlResource(18, "text/css") },
                { "/css/svg/settings-icon.svg", new HtmlResource(3, "image/svg+xml") },
                { "/css/fonts/NotoSans-Regular.ttf", new HtmlResource(4, "application/font") },
                { "/css/fonts/NotoSans-Light.ttf", new HtmlResource(5, "application/font") },
                { "/css/fonts/NotoSans-Thin.ttf", new HtmlResource(6, "application/font") },
                { "/html/foundbeatmaps.html", new HtmlResource(10, "text/html") },
                { "/css/svg/close-icon.svg", new HtmlResource(11, "image/svg+xml") },
                { "/jquery", new HtmlResource(12, "application/javascript") },
                { "/gifs/loading.gif", new HtmlResource(14, "image/gif") },
                { "/gifs/loading_dark.gif", new HtmlResource(19, "image/gif") },
                { "/css/svg/save.svg", new HtmlResource(15, "image/svg+xml") },
                { "/css/svg/clear.svg", new HtmlResource(16, "image/svg+xml") },
                { "/html/beatmap_downloader.html", new HtmlResource(20, "text/html") },
                { "/html/search_dl.html", new HtmlResource(21, "text/html") },
                { "/css/svg/downloader-icon.svg", new HtmlResource(22, "image/svg+xml") },
                { "/css/svg/downloader-bracket-icon.svg", new HtmlResource(23, "image/svg+xml") },
                { "/progressbar.js", new HtmlResource(24, "application/javascript") },
                { "/html/list_dl.html", new HtmlResource(25, "text/html") },
                { "/preview_player.js", new HtmlResource(27, "application/javascript") },
                { "/css/standard_mode.png", new HtmlResource(30, "image/png") },
                { "/css/taiko_mode.png", new HtmlResource(31, "image/png") },
                { "/css/ctb_mode.png", new HtmlResource(32, "image/png") },
                { "/css/mania_mode.png", new HtmlResource(33, "image/png") },
                { "/css/standard_mode_light.png", new HtmlResource(40, "image/png") },
                { "/css/taiko_mode_light.png", new HtmlResource(41, "image/png") },
                { "/css/ctb_mode_light.png", new HtmlResource(42, "image/png") },
                { "/css/mania_mode_light.png", new HtmlResource(43, "image/png") },
                { "/css/preview_stop.png", new HtmlResource(50, "image/png") },
                { "/css/preview_play.png", new HtmlResource(51, "image/png") },
                { "/rightbuttonmenu.js", new HtmlResource(70, "application/javascript") },
            };
        }
Example #10
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="gert">Add-on card controller.</param>
        /// <param name="mc">Motor controller.</param>
        public GpioController(GertbotUartController gert, MotorController mc)
        {
            this.gertController  = gert;
            this.motorController = mc;

            this.semaphore = new System.Threading.SemaphoreSlim(
                1, // Initial count > 0: the semaphore is initially free
                1  // Max count: only one thread can enter at a time
                );
        }
Example #11
0
        public CacheService()
        {
            _dataProviders = new ConcurrentDictionary <CacheContentType, Func <string, Task <object> > >();
            _items         = new ConcurrentDictionary <Tuple <CacheContentType, string>, CacheItem>();

            _cacheStatsTimer          = new Timer(CacheStatsIntervalMinutes * 60 * 1000);
            _cacheStatsTimer.Elapsed += CacheStatsTimerOnElapsed;
            _cacheStatsTimer.Start();

            _cacheLock = new System.Threading.SemaphoreSlim(1, 1);
        }
        /// <summary>
        /// Set levelOfParallelism from 1 to 128
        /// </summary>
        /// <param name="levelOfParallelism"></param>
        public TaskBatchRunner(int levelOfParallelism = 10)
        {
            if (levelOfParallelism < 1)
            {
                levelOfParallelism = 1;
            }
            if (levelOfParallelism > 128)
            {
                levelOfParallelism = 128;
            }

            _semaphoreSlim = new System.Threading.SemaphoreSlim(levelOfParallelism, levelOfParallelism);
        }
Example #13
0
            public KeyValueItemBar()
            {
                this.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = new GridLength(1, GridUnitType.Star)
                });
                this.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = new GridLength(2, GridUnitType.Star)
                });
                this.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = new GridLength(40, GridUnitType.Absolute)
                });
                {
                    ETkey = new MyEntry();
                    ETkey.SetBinding(MyEntry.TextProperty, "Key", BindingMode.TwoWay);
                    this.Children.Add(ETkey, 0, 0);
                }
                {
                    ETvalue = new MyEntry();
                    ETvalue.SetBinding(MyEntry.TextProperty, "Value", BindingMode.TwoWay);
                    this.Children.Add(ETvalue, 1, 0);
                }
                {
                    BTNcancel          = new MyButton("\u2716");//✖
                    BTNcancel.Clicked += async delegate
                    {
                        if (this.BindingContext != null) // && await MyLogger.Ask($"Remove this item?\r\nKey: {ETkey.Text}\r\nValue: {ETvalue.Text}"))
                        {
                            await(this.BindingContext as MyControls.BarsListPanel.MyDisposable).OnDisposed();
                        }
                    };
                    this.Children.Add(BTNcancel, 2, 0);
                }
                System.Threading.SemaphoreSlim semaphoreSlim = new System.Threading.SemaphoreSlim(1, 1);
                this.Appeared += async(sender) =>
                {
                    this.Opacity = 0;
                    await semaphoreSlim.WaitAsync();

                    //this.Opacity = 1;
                    await this.FadeTo(1, 500);

                    lock (semaphoreSlim) semaphoreSlim.Release();
                };
                this.Disappearing = new Func <Task>(async() =>
                {
                    await semaphoreSlim.WaitAsync();
                    //this.Opacity = 0;
                    await this.FadeTo(0, 500);
                    lock (semaphoreSlim) semaphoreSlim.Release();
                });
            }
Example #14
0
        public async System.Threading.Tasks.Task <SoftmakeAll.SDK.OperationResult> CopyAsync(System.String SourceBucketName, System.String[] SourceStorageFileNames, System.String TargetBucketName, System.String[] TargetStorageFileNames, System.Boolean Overwrite)
        {
            SoftmakeAll.SDK.CloudStorage.AWS.Environment.Validate();

            SoftmakeAll.SDK.OperationResult OperationResult = new SoftmakeAll.SDK.OperationResult();

            if ((System.String.IsNullOrWhiteSpace(SourceBucketName)) || (SourceStorageFileNames == null) || (SourceStorageFileNames.Length == 0) || (System.String.IsNullOrWhiteSpace(TargetBucketName)) || (TargetStorageFileNames == null) || (TargetStorageFileNames.Length == 0))
            {
                OperationResult.Message = "The SourceBucketName, SourceStorageFileNames, TargetBucketName and TargetStorageFileNames cannot be null.";
                return(OperationResult);
            }

            if (SourceStorageFileNames.Length != TargetStorageFileNames.Length)
            {
                OperationResult.Message = "The SourceStorageFileNames and TargetStorageFileNames must be the same length.";
                return(OperationResult);
            }

            try
            {
                using (System.Threading.SemaphoreSlim SemaphoreSlim = new System.Threading.SemaphoreSlim(SourceStorageFileNames.Length))
                {
                    System.Collections.Generic.List <System.Threading.Tasks.Task> CopyTasks = new System.Collections.Generic.List <System.Threading.Tasks.Task>();
                    for (System.Int32 i = 0; i < SourceStorageFileNames.Length; i++)
                    {
                        await SemaphoreSlim.WaitAsync();

                        CopyTasks.Add(System.Threading.Tasks.Task.Run(async() =>
                        {
                            await SoftmakeAll.SDK.CloudStorage.AWS.Environment._S3Client.CopyObjectAsync(new Amazon.S3.Model.CopyObjectRequest {
                                SourceBucket = SourceBucketName, SourceKey = SourceStorageFileNames[i], DestinationBucket = TargetBucketName, DestinationKey = TargetStorageFileNames[i]
                            });
                            SemaphoreSlim.Release();
                        }));
                    }

                    if (CopyTasks.Any())
                    {
                        await System.Threading.Tasks.Task.WhenAll(CopyTasks);
                    }
                }
            }
            catch (System.Exception ex)
            {
                OperationResult.Message = ex.Message;
                return(OperationResult);
            }

            OperationResult.ExitCode = 0;
            return(OperationResult);
        }
Example #15
0
        static StackObject *Ctor_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Int32 @initialCount = ptr_of_this_method->Value;


            var result_of_this_method = new System.Threading.SemaphoreSlim(@initialCount);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
        public static async Task RunAsync(this System.Threading.SemaphoreSlim semaphore, Func <Task> action,
                                          System.Threading.CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
                await action().ConfigureAwait(false);
            }
            finally
            {
                semaphore.Release();
            }
        }
        public async System.Threading.Tasks.Task <SoftmakeAll.SDK.OperationResult> DeleteAsync(System.String ShareName, System.String[] StorageFileNames)
        {
            SoftmakeAll.SDK.CloudStorage.Azure.Environment.Validate();

            SoftmakeAll.SDK.OperationResult OperationResult = new SoftmakeAll.SDK.OperationResult();

            if ((System.String.IsNullOrWhiteSpace(ShareName)) || (StorageFileNames == null) || (StorageFileNames.Length == 0))
            {
                OperationResult.Message = "The ShareName and StorageFileName cannot be null.";
                return(OperationResult);
            }

            try
            {
                global::Azure.Storage.Files.Shares.ShareClient          ShareClient          = new global::Azure.Storage.Files.Shares.ShareClient(SoftmakeAll.SDK.CloudStorage.Azure.Environment._ConnectionString, ShareName);
                global::Azure.Storage.Files.Shares.ShareDirectoryClient ShareDirectoryClient = ShareClient.GetRootDirectoryClient();

                using (System.Threading.SemaphoreSlim SemaphoreSlim = new System.Threading.SemaphoreSlim(StorageFileNames.Length))
                {
                    System.Collections.Generic.List <System.Threading.Tasks.Task> DeleteTasks = new System.Collections.Generic.List <System.Threading.Tasks.Task>();
                    foreach (System.String StorageFileName in StorageFileNames)
                    {
                        global::Azure.Storage.Files.Shares.ShareFileClient ShareFileClient = ShareDirectoryClient.GetFileClient(StorageFileName);
                        if (!(await ShareFileClient.ExistsAsync()))
                        {
                            continue;
                        }

                        await SemaphoreSlim.WaitAsync();

                        DeleteTasks.Add(System.Threading.Tasks.Task.Run(async() => { await ShareFileClient.DeleteAsync(); SemaphoreSlim.Release(); }));
                    }

                    if (DeleteTasks.Any())
                    {
                        await System.Threading.Tasks.Task.WhenAll(DeleteTasks);
                    }
                }
            }
            catch (System.Exception ex)
            {
                OperationResult.Message = ex.Message;
                return(OperationResult);
            }

            OperationResult.ExitCode = 0;
            return(OperationResult);
        }
Example #18
0
        static StackObject *Release_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Threading.SemaphoreSlim instance_of_this_method = (System.Threading.SemaphoreSlim) typeof(System.Threading.SemaphoreSlim).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.Release();

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method;
            return(__ret + 1);
        }
Example #19
0
        public MySwitch(string onText, string offText, bool onLeft = true) : this()
        {
            {
                MyLabel lbl = new MyLabel(offText)
                {
                    IsVisible = false, Opacity = 0, FontAttributes = FontAttributes.Bold, VerticalTextAlignment = TextAlignment.Center
                };
                if (onLeft)
                {
                    MyGrid.SetColumn(SWmain, 1);
                    this.Children.Add(lbl, 0, 0);
                }
                else
                {
                    this.Children.Add(lbl, 1, 0);
                }
                System.Threading.SemaphoreSlim semaphoreSlim = new System.Threading.SemaphoreSlim(1, 1);
                bool animationCompletedWith = false;
                SWmain.Toggled += async delegate
                {
                    bool backUp = SWmain.IsToggled;
                    try
                    {
                        await semaphoreSlim.WaitAsync();

                        lbl.Text = (SWmain.IsToggled ? onText : offText);
                        if (backUp != SWmain.IsToggled || animationCompletedWith == backUp)
                        {
                            return;
                        }
                        lbl.IsVisible = true;
                        await lbl.FadeTo(1);

                        await Task.Delay(1000);

                        await lbl.FadeTo(0);

                        lbl.IsVisible          = false;
                        animationCompletedWith = backUp;
                    }
                    finally
                    {
                        lock (semaphoreSlim) semaphoreSlim.Release();
                    }
                };
            }
        }
Example #20
0
        /// <summary>
        /// Disposes the object.
        /// </summary>
        public void Dispose()
        {
            if (this.dataReaderObject != null)
            {
                try
                {
                    this.dataReaderObject.DetachStream();
                    this.dataReaderObject.Dispose();
                    this.dataReaderObject = null;
                }
                catch { }
            }

            if (this.dataWriterObject != null)
            {
                try
                {
                    this.dataWriterObject.DetachStream();
                    this.dataWriterObject.Dispose();
                    this.dataWriterObject = null;
                }
                catch { }
            }

            if (this.serialPort != null)
            {
                try
                {
                    this.serialPort.Dispose();
                    this.serialPort = null;
                }
                catch { }
            }

            if (this.semaphore != null)
            {
                try
                {
                    this.semaphore.Dispose();
                    this.semaphore = null;
                }
                catch { }
            }
        }
Example #21
0
        static StackObject *WaitAsync_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Threading.SemaphoreSlim instance_of_this_method = (System.Threading.SemaphoreSlim) typeof(System.Threading.SemaphoreSlim).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.WaitAsync();

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Example #22
0
        public FileTransferContentView()
        {
            System.Threading.SemaphoreSlim semaphoreSlim = new System.Threading.SemaphoreSlim(1, 1);
            var newTaskCreatedEventHandler = new CloudFile.Networker.NewTaskCreatedEventHandler((networker) =>
            {
                OnStatusEnter(networker, previousStatus[networker] = networker.Status);
                var statusChangedEventHandler = new CloudFile.Networker.NetworkStatusChangedEventHandler(async() =>
                {
                    await semaphoreSlim.WaitAsync();
                    OnStatusLeave(networker, previousStatus[networker]);
                    OnStatusEnter(networker, previousStatus[networker] = networker.Status);
                    lock (semaphoreSlim) semaphoreSlim.Release();
                    if (networker.Status == CloudFile.Networker.NetworkStatus.ErrorNeedRestart)
                    {
                        if (todoWhenTaskFailed != null)
                        {
                            await todoWhenTaskFailed(networker);
                        }
                    }
                });
                networker.StatusChanged += statusChangedEventHandler;
                var data = new NetworkingItemBarViewModel(networker);
                MyControls.BarsListPanel.MyDisposable.MyDisposableEventHandler dataDisposedEventHandler = null;
                dataDisposedEventHandler = new MyControls.BarsListPanel.MyDisposable.MyDisposableEventHandler(async delegate
                {
                    networker.StatusChanged -= statusChangedEventHandler;
                    data.Disposed           -= dataDisposedEventHandler;
                    await semaphoreSlim.WaitAsync();
                    OnStatusLeave(networker, previousStatus[networker]);
                    previousStatus.Remove(networker);
                    lock (semaphoreSlim) semaphoreSlim.Release();
                });
                data.Disposed += dataDisposedEventHandler;
                this.PushBack(data);
            });

            CloudFile.Modifiers.FolderCreator.NewFolderCreateCreated    += newTaskCreatedEventHandler;
            CloudFile.Downloaders.FileDownloader.NewFileDownloadCreated += newTaskCreatedEventHandler;
            CloudFile.Uploaders.FileUploader.NewFileUploadCreated       += newTaskCreatedEventHandler;
            CloudFile.Uploaders.FolderUploader.NewFolderUploadCreated   += newTaskCreatedEventHandler;
        }
Example #23
0
        public NetworkingItemBar()
        {
            InitializeViews();
            System.Threading.SemaphoreSlim semaphoreSlim = new System.Threading.SemaphoreSlim(1, 1);
            this.Appeared += async(sender) =>
            {
                this.Opacity = 0;
                await semaphoreSlim.WaitAsync();

                //this.Opacity = 1;
                await this.FadeTo(1, 500);

                lock (semaphoreSlim) semaphoreSlim.Release();
            };
            this.Disappearing = new Func <Task>(async() =>
            {
                await semaphoreSlim.WaitAsync();
                //this.Opacity = 0;
                await this.FadeTo(0, 500);
                lock (semaphoreSlim) semaphoreSlim.Release();
            });
        }
Example #24
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);
        }
Example #25
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);
        }
        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);
        }
Example #27
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);
        }
Example #28
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);
        }
Example #29
0
        public static async Task <T> DeserializeAsync <T>(Windows.Storage.StorageFolder folder, string fileName, System.Threading.SemaphoreSlim semaphore) where T : class
        {
            await semaphore.WaitAsync();

            try
            {
                if (await folder.TryGetItemAsync(fileName) is Windows.Storage.StorageFile f)
                {
                    using (var s = (await f.OpenAsync(Windows.Storage.FileAccessMode.Read)).AsStream())
                    {
                        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                        return((T)serializer.Deserialize(s));
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch
            {
                return(null);
            }
            finally
            {
                semaphore.Release();
            }
        }
Example #30
0
        public static async Task SerializeAsync <T>(T content, Windows.Storage.StorageFolder folder, string fileName, System.Threading.SemaphoreSlim semaphore)
        {
            await semaphore.WaitAsync();

            try
            {
                var f = await folder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                using (var s = (await f.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)).AsStream())
                {
                    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    serializer.Serialize(s, content);
                }
            }
            catch { }
            finally
            {
                semaphore.Release();
            }
        }
Example #31
0
        private static async Task <BookInfo[]> LoadAsyncOne(Windows.Storage.StorageFile file, System.Threading.SemaphoreSlim sem)
        {
            if (file == null)
            {
                return(null);
            }

            await sem.WaitAsync();

            try
            {
                using (var s = (await file.OpenAsync(Windows.Storage.FileAccessMode.Read)).AsStream())
                {
                    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(BookInfo[]));
                    return((BookInfo[])serializer.Deserialize(s));
                }
            }
            catch
            {
                return(null);
            }
            finally
            {
                sem.Release();
            }
        }
Example #32
0
 public Stream(CircleInfo source, StreamManager manager)
 {
     _activities = new ObservableCollection<Activity>();
     _syncer = new System.Threading.SemaphoreSlim(1, 1);
     Circle = source;
 }