/// <summary>
        /// Initialize cloud state
        /// </summary>
        public async Task InitAsync()
        {
            if (isInitialized)
            {
                return;
            }

            await semaphoreSlim.WaitAsync().ConfigureAwait(false);

            try
            {
                if (!isInitialized)
                {
                    await UpdateAsync().ConfigureAwait(false);

                    if (zooKeeper.getState() != ZooKeeper.States.CONNECTED && zooKeeper.getState() != ZooKeeper.States.CONNECTEDREADONLY)
                    {
                        throw new Exceptions.SolrNetCloudConnectionException($"Cannot connect to the Zookeeper instance {zooKeeperConnection}. Current state: {zooKeeper.getState()} ");
                    }

                    isInitialized = true;
                }
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
        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 #3
0
        /// <summary>
        /// Connects to the server with the provided details
        /// </summary>
        /// <param name="nick">Nickname to use</param>
        /// <param name="user">Username to use</param>
        /// <param name="realname">Real name to use</param>
        /// <param name="host">Host to which to connect</param>
        /// <param name="port">Port on which to connect</param>
        /// <param name="password">Password to send on connect</param>
        /// <returns></returns>
        public async Task Connect(String nick, String user, String realname, String host, int port = 6667, String password = null)
        {
            lock (_registrationLock)
            {
                Disconnect();
                // Establish connection
                Nick = nick; Username = user; RealName = realname; Host = host; Port = port; Password = password;
                TCP  = new TcpClient();
            }
            Task  connectTask = TCP.ConnectAsync(host, port);
            await connectTask;

            if (connectTask.Exception != null)
            {
                Exception = connectTask.Exception;
                if (OnException != null)
                {
                    foreach (var d in OnException.GetInvocationList())
                    {
                        var task = Task.Run(() => d.DynamicInvoke(this, connectTask.Exception));
                    }
                }
                throw connectTask.Exception; // If connect failed
            }

            Connected = true;

            // If connect succeeded

            streamReader = new System.IO.StreamReader(TCP.GetStream(), Encoding);
            streamWriter = new System.IO.StreamWriter(TCP.GetStream(), Encoding);

            // Register handler to on connect event
            OnRawMessageReceived += RegisterHandler;

            await _streamSemaphore.WaitAsync();

            try
            {
                var readLineTask = streamReader.ReadLineAsync().ContinueWith(OnAsyncRead);
            }
            catch (Exception e)
            {
                Exception = e;
                if (OnException != null)
                {
                    foreach (var d in OnException.GetInvocationList())
                    {
                        var task = Task.Run(() => d.DynamicInvoke(this, e));
                    }
                }
            }
            finally
            {
                _streamSemaphore.Release();
            }
        }
Example #4
0
 private void AddToCache(ILogItem item)
 {
     semapore.Wait();
     try { _logCache.Add(item); }
     finally { semapore.Release(); }
     if (_logCache.Count >= _cacheMaxEntries)
     {
         SaveCache();
     }
 }
Example #5
0
 public static void StdErrLog(string message, EventLogEntryType eventLogEntryType = EventLogEntryType.Information)
 {
     consoleErrorLock.Wait();
     try {
         System.Console.Error.WriteLine(GetConsoleLogString(message, eventLogEntryType));
     }
     finally {
         consoleErrorLock.Release();
     }
 }
Example #6
0
 private void Execute(Action method)
 {
     ss.Wait();
     try { method.Invoke(); }
     catch (Exception ex)
     {
         logger.FatalException(method.Method + " failed", ex); throw;
     }
     finally { ss.Release(); }
 }
Example #7
0
        public static async Task <PurchaseHistory> GetPurchaseHistory()
        {
            try
            {
                await semaphore.WaitAsync();

                if (Content != null)
                {
                    return(Content);
                }
                if (!System.IO.File.Exists(Path))
                {
                    return(Content = new PurchaseHistory());
                }
                try
                {
                    Content = await SerializationHelper.DeserializeAsync <PurchaseHistory>(Path);

                    if (Content != null)
                    {
                        return(Content);
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("Failed to load'{0}'", Path));
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
                try
                {
                    Content = await SerializationHelper.DeserializeAsync <PurchaseHistory>(PathBup);

                    if (System.IO.File.Exists(Path))
                    {
                        System.IO.File.Delete(Path);
                    }
                    if (System.IO.File.Exists(PathBup))
                    {
                        System.IO.File.Move(PathBup, Path);
                    }
                    return(Content = Content ?? new PurchaseHistory());
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("Failed to load'{0}'", PathBup));
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
                return(Content = new PurchaseHistory());
            }
            finally
            {
                semaphore.Release();
            }
        }
Example #8
0
        /// <summary>
        /// This is the event handler for PrintDocument.Paginate. It creates print preview pages for the app.
        /// </summary>
        /// <param name="sender">PrintDocument</param>
        /// <param name="e">Paginate Event  </param>
        public virtual async void CreatePrintPreviewPages(object sender, PaginateEventArgs e)
        {
            var paperSize = e.PrintTaskOptions.GetPageDescription(0).PageSize;

            System.Diagnostics.Debug.WriteLine("CreatePrintPreviewPages: {" + paperSize.Width + "," + paperSize.Height + "}");

            //lock (printPreviewPages)
            await _semaphoreSlim.WaitAsync();

            {
                // Clear the cache of preview pages
                printPreviewPages.Clear();

                // Clear the print canvas of preview pages
                PrintCanvas.Children.Clear();

                // Get the PrintTaskOptions
                PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions);

                // Get the page description to deterimine how big the page is
                PrintPageDescription pageDescription = printingOptions.GetPageDescription(0);



                if (await GeneratePagesAsync(pageDescription) is List <UIElement> pages)
                {
                    foreach (var page in pages)
                    {
                        PrintCanvas.Children.Add(page);
                    }
                    PrintCanvas.InvalidateMeasure();
                    PrintCanvas.UpdateLayout();

                    await Task.Delay(1000);

                    printPreviewPages.AddRange(pages);
                    await Task.Delay(1000);
                }

                if (PreviewPagesCreated != null)
                {
                    PreviewPagesCreated.Invoke(printPreviewPages, null);
                }

                PrintDocument printDoc = (PrintDocument)sender;

                // Report the number of preview pages created
                printDoc.SetPreviewPageCount(printPreviewPages.Count, PreviewPageCountType.Intermediate);
            }
            _semaphoreSlim.Release();
        }
Example #9
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 #10
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);
                    }
                }
            }
        }
Example #11
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 #12
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 async Task ProcessExecutionTraceAnalysis(ExecutionTraceAnalysis traceAnalysis)
        {
            // Obtain our thread ID
            int threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

            // Create a thread state for this thread
            MeadowDebugAdapterThreadState threadState = new MeadowDebugAdapterThreadState(traceAnalysis, threadId);

            // Acquire the semaphore for processing a trace.
            await _processTraceSemaphore.WaitAsync();

            // Set the thread state in our lookup
            ThreadStates[threadId] = threadState;

            // Send an event that our thread has exited.
            Protocol.SendEvent(new ThreadEvent(ThreadEvent.ReasonValue.Started, threadState.ThreadId));

            // Continue our execution.
            ContinueExecution(threadState, DesiredControlFlow.Continue);

            // Lock execution is complete.
            await threadState.Semaphore.WaitAsync();

            // Remove the thread from our lookup.
            ThreadStates.Remove(threadId, out _);

            // Unlink our data for our thread id.
            ReferenceContainer.UnlinkThreadId(threadId);

            // Send an event that our thread has exited.
            Protocol.SendEvent(new ThreadEvent(ThreadEvent.ReasonValue.Exited, threadState.ThreadId));

            // Release the semaphore for processing a trace.
            _processTraceSemaphore.Release();
        }
        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();
            }
        }
Example #15
0
        private static async void AnalyticsManager_OnUpdate()
        {
            await analyticsUpdateSyncRoot.WaitAsync();

            try
            {
                var updates = new Dictionary <BaseSubscription, SubscriptionUpdateBase>();
                foreach (var subscription in InfoConnectionManager.GetActiveSubscriptions())
                {
                    var update = default(SubscriptionUpdateBase);
                    switch (subscription)
                    {
                    case DepthsSubscription depthsSubscription:
                    {
                        var depth = AnalyticsManager.MarketDepthsManager.GetDepth(depthsSubscription.Market, depthsSubscription.Precision);
                        update = MarketDepthUpdate.Generate(depth, depthsSubscription.Name);
                    }
                    break;

                    case PriceHistorySubscription priceHistorySubscription:
                    {
                        var priceFrames = await AnalyticsManager.PriceHistoryManager.GetPriceHistory(0, priceHistorySubscription.Market, priceHistorySubscription.FramePeriod);

                        update = PriceHistoryUpdate.Generate(priceFrames.frames, priceHistorySubscription.Name);
                    }
                    break;

                    case TradesFeedSubscription tradesFeedSubscription:
                    {
                        var trades = AnalyticsManager.TradesHistoryManager.GetTrades(tradesFeedSubscription.Market);
                        update = TradesFeedUpdate.Generate(trades, tradesFeedSubscription.Name);
                    }
                    break;

                    case AllMarketTickersSubscription allMarketTickersSubscription:
                    {
                        var allTickers = AnalyticsManager.MarketTickersManager.GetAllTickers();
                        update = AllTickersUpdate.Generate(allTickers, allMarketTickersSubscription.Name);
                    }
                    break;

                    case MarketTickerSubscription marketTickerSubscription:
                    {
                        var marketTicker = AnalyticsManager.MarketTickersManager.GetMarketTicker(marketTickerSubscription.Market);
                        update = MarketTickerUpdate.Generate(marketTicker, marketTickerSubscription.Name);
                    }
                    break;
                    }
                    if (update != null)
                    {
                        updates.Add(subscription, update);
                    }
                }
                InfoConnectionManager.SendSubscriptionUpdates(updates);
            }
            finally
            {
                analyticsUpdateSyncRoot.Release();
            }
        }
Example #16
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 #17
0
        public async Task SetPressurePercent(double newPercent)
        {
            await pneumaticSemaphore.WaitAsync();

            try
            {
                var deltaPercent = newPercent - PressurePercent;

                if (deltaPercent > 0)
                {
                    // Requires inflation
                    var inflationDurationS = deltaPercent / pneumatic.InflationRatePctPerS;
                    if (newPercent >= 1)
                    {
                        inflationDurationS += 0.25 / pneumatic.InflationRatePctPerS;    // Extra padding to ensure maximum inflation
                    }
                    await pneumatic.Inflate(inflationDurationS);
                }
                else if (deltaPercent < 0)
                {
                    var deflationDurationS = (-deltaPercent) / pneumatic.DeflationRatePctPerS;
                    if (newPercent <= 0)
                    {
                        deflationDurationS += 0.25 / pneumatic.DeflationRatePctPerS;    // Extra padding to ensure absolute zero
                    }
                    await pneumatic.Deflate(deflationDurationS);
                }
                this.PressurePercent = newPercent;
            }
            finally
            {
                pneumaticSemaphore.Release();
            }
        }
Example #18
0
        public static async Task SerializeAsync <T>(T data, string path)
        {
            await semaphore.WaitAsync();

            try
            {
                var xs = new XmlSerializer(typeof(T));
                using (var sw = new StreamWriter(path))
                {
                    await Task.Run(() => { try { xs.Serialize(sw, data); } catch { } });
                }
            }
            finally
            {
                semaphore.Release();
            }
        }
    private void OnTimer(object state)
    {
        var requests = Interlocked.Exchange(ref _currentRequests, 0);

        if (requests > 0)
        {
            _semaphore.Release(requests);
        }
    }
Example #20
0
    private void OnTimer(object state)
    {
        var releaseCount = Interlocked.Exchange(ref _releaseCount, 0);

        if (releaseCount > 0)
        {
            _semaphore.Release(releaseCount);
        }
    }
Example #21
0
        // シリアライズする
        public static async Task SerializeAsync <T>(T data, string filePath)
        {
            await _semaphore.WaitAsync(); // ロックを取得する

            try
            {
                var xmlSerializer = CachingXmlSerializerFactory.Create(typeof(T));
                using (var streamWriter = new StreamWriter(filePath, false, new UTF8Encoding(false)))
                {
                    await Task.Run(() => xmlSerializer.Serialize(streamWriter, data));

                    await streamWriter.FlushAsync();  // .NET Framework 4.5以降
                }
            }
            finally
            {
                _semaphore.Release(); // ロックを解放する
            }
        }
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 async Task <TData> GetAsync <TData>(CacheContentType type, string parameter = null)
        {
            await _cacheLock.WaitAsync();

            try
            {
                if (!_dataProviders.TryGetValue(type, out var dataProvider))
                {
                    throw new NoDataProviderException($"{type} data provider doesn't exist in cache.");
                }

                if (!_items.ContainsKey(new Tuple <CacheContentType, string>(type, parameter)))
                {
                    var data = await FetchDataFromProvider(dataProvider, parameter, null);

                    _items.TryAdd(new Tuple <CacheContentType, string>(type, parameter), new CacheItem(data));
                    _cacheItemsAdded++;

                    _logger.Info($"Cache data added ({type})");

                    ApplyPatches(type, data);
                    return((TData)data);
                }

                var cachedItem        = _items[new Tuple <CacheContentType, string>(type, parameter)];
                var lifetimeAttribute = type.GetEnumMemberAttribute <CacheLifetimeAttribute>(type);

                if ((DateTime.Now - cachedItem.UpdateTime).TotalMinutes >= lifetimeAttribute.Lifetime)
                {
                    var data = await FetchDataFromProvider(dataProvider, parameter, cachedItem.Data);

                    if (data != cachedItem.Data)
                    {
                        ApplyPatches(type, data);
                        cachedItem.Update(data);

                        _logger.Info($"Cache data updated ({type})");
                    }

                    _cacheItemsUpdated++;
                }
                else
                {
                    _cacheItemsHit++;
                }

                return((TData)cachedItem.Data);
            }
            finally
            {
                _cacheLock.Release();
            }
        }
        private async void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem == null || !(e.SelectedItem is IWordViewModel))
            {
                return;
            }
            if (Pushing)
            {
                return;
            }
            try
            {
                Pushing = true;
                await WordsPageSemaphore.WaitAsync();

                if (!Pushing)
                {
                    return;
                }

                if (this.Model.Words.Count > 300)
                {
                    var page = new WordPage((IWordViewModel)e.SelectedItem);
                    await Navigation.PushAsync(page);
                }
                else
                {
                    var page = WordsPage;
                    try
                    {
                        await page.CanPushSemaphore.WaitAsync();

                        page.SelectedItem = (IWordViewModel)e.SelectedItem;
                        if (page.Parent == null)
                        {
                            await Navigation.PushAsync(page);
                        }
                    }
                    finally
                    {
                        page.CanPushSemaphore.Release();
                    }
                }
            }
            catch { }
            finally
            {
                WordsPageSemaphore.Release();
                Pushing = false;
            }

            (sender as ListView).SelectedItem = null;
        }
Example #25
0
    static async Task F(int i)
    {
        Console.WriteLine($"F{i} starts on " + GetCurrentThreadId());
        await Semaphore.WaitAsync();

        Console.WriteLine($"F{i} continues on " + GetCurrentThreadId());
        await Task.Delay(6000);         //.ConfigureAwait(false); //<- uncomment to solve deadlock

        Console.WriteLine($"F{i} ends on " + GetCurrentThreadId());
        Semaphore.Release(1);
        //DeadLock();
    }
Example #26
0
        public static async Task <Place> PlaceFromNameAsync(string name)
        {
            var newNumFormat = (System.Globalization.NumberFormatInfo)System.Globalization.NumberFormatInfo.CurrentInfo.Clone();

            newNumFormat.NumberDecimalSeparator = ".";      //tizedespont tizedesvessző helyett
            XDocument xdoc;
            await semaphore.WaitAsync();

            do
            {
                string content = "";        //üres string, hogy VisualStudio ne panaszkodjon
                bool   isValid = false;
                do
                {
                    try
                    {
                        content = await httpClient.GetStringAsync(geoLocApi + name);

                        isValid = true;
                        xdoc    = XDocument.Parse(content);
                    }
                    catch (HttpRequestException)
                    {
                        isValid = false;        //az kellene legyen alapból, de a biztonság kedvéért...
                        await Task.Delay(20);   //kis delay
                    }
                } while (!isValid);
                xdoc = XDocument.Parse(content);
            } while (xdoc.Root.Element("status").Value == "OVER_QUERY_LIMIT");
            semaphore.Release();
            if (xdoc.Root.Element("status").Value == "ZERO_RESULTS")
            {
                Console.WriteLine("Zero results: {0}", name);
                return(null);        //null-lal jelezzük, hogy nincs ilyen hely
            }
            string country;

            if (xdoc.Descendants("address_component").Descendants("type").Where(x => x.Value == "country").Count() != 0)
            {
                country = xdoc.Descendants("address_component").Descendants("type").Where(x => x.Value == "country").First().Parent.Element("long_name").Value;
            }
            else
            {
                country = "-";
            }
            return(new Place(
                       name,
                       country,
                       xdoc.Descendants("formatted_address").First().Value,
                       Convert.ToDouble(xdoc.Root.Descendants("location").First().Element("lat").Value, newNumFormat),
                       double.Parse(xdoc.Root.Descendants("location").First().Element("lng").Value, newNumFormat)));
        }
Example #27
0
        public async Task <MessageResult> Handle(CreateBooking message)
        {
            await semaphoreSlim.WaitAsync();

            try
            {
                // TODO validations etc.
                var startAt   = DateTime.Parse(message.StartAt);
                var serviceId = int.Parse(message.ServiceId);

                if (await unitOfWork.Exists <Booking>(b => b.StartAt == startAt && b.ServiceId == serviceId))
                {
                    throw new Domain.BookingAlreadyExists();
                }

                var createdUtc = DateTime.UtcNow;
                var booking    = new Booking
                {
                    Email            = message.Email,
                    Name             = message.Name,
                    Surname          = message.Surname,
                    Phone            = message.Phone,
                    BookingAt        = DateTime.Parse(message.BookingAt),
                    StartAt          = startAt,
                    ServiceId        = serviceId,
                    Quantity         = int.Parse(message.Quantity),
                    Price            = decimal.Parse(message.Price),
                    Comment          = message.Comment,
                    BookingCreatedAt = createdUtc,
                    Status           = (int)Domain.BookingStatus.Created
                };
                await unitOfWork.Add(booking);

                await unitOfWork.Save();

                var bookingCreated = new Domain.BookingCreated
                {
                    CreatedAt = createdUtc,
                    BookingId = booking.Id,
                };

                await unitOfWork.Add(BookingEvent.CreateFrom(bookingCreated));

                await unitOfWork.Save();

                return(new MessageResult(201, new { booking.Id }));
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
        public async Task Run(Func <Task> handler)
        {
            await _semaphoreSlim.WaitAsync();

            try
            {
                await handler();
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }
Example #29
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 #30
0
        private async Task ExclusiveAsync(Func <Task> funcAsync)
        {
            await _semaphore.WaitAsync();

            try
            {
                await funcAsync();
            }
            finally
            {
                _semaphore.Release();
            }
        }