示例#1
0
        private void FilterText_KeyUp(object sender, KeyEventArgs e)
        {
            FilterText.Text = FilterText.Text.Trim();
            if (FilterText.Text != "")
            {
                // フィルタリング処理は、タイマーで時間差を置いて処理する

                if (filterProcTimer.IsEnabled)
                {
                    filterProcTimer.Stop();
                    filterProcTimer.Start();
                    return;
                }

                treeViewCommand.Visibility       = Visibility.Collapsed;
                searchTreeViewCommand.Visibility = Visibility.Visible;
                filterProcTimer.IsEnabled        = true;
                filterProcTimer.Start();
            }
            else
            {
                // フィルタリング解除

                treeViewCommand.Visibility       = Visibility.Visible;
                searchTreeViewCommand.Visibility = Visibility.Collapsed;
                cancellationTokenSource?.Cancel();
                cancellationTokenSource = null;
                filterProcTimer.Stop();
                filterProcTimer.IsEnabled = false;
            }
        }
示例#2
0
        public static void Stop(string name = "")
        {
            try
            {
                cancellationToken?.Cancel();
                cancellationToken?.Dispose();
                cancellationToken = null;

                if (!string.IsNullOrEmpty(name))
                {
                    var n = name.LastIndexOf(".");
                    name = name.Substring(0, n) + "_cmd.ini";
                    if (File.Exists(name))
                    {
                        var lines = File.ReadAllLines(name).Where(l => l.StartsWith("stop", StringComparison.OrdinalIgnoreCase)).ToArray();
                        if (lines.Length > 0)
                        {
                            Task.Run(() =>
                            {
                                foreach (var item in lines)
                                {
                                    Send(item.Substring(5));
                                    Task.Delay(100).Wait();
                                }
                            });
                        }
                    }
                }
            }
            catch { }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            System.Collections.IEnumerable source = sender as System.Collections.IEnumerable;

            if (source != null)
            {
                cancel?.Cancel();
                cancel = new System.Threading.CancellationTokenSource();
                Task.Run(() => {
                    try
                    {
                        cachedSource = GenerateItems(source);
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            RecreateItems();
                        });
                        cancel = null;
                    }
                    catch {
                        // ignore everything...
                    }
                }, cancel.Token);
            }
            else
            {
                layout.Children.Clear();
                this.Learning = true;
                RecreateItems();
            }
        }
示例#4
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Check the task cost
            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
            if (cost == BackgroundWorkCostValue.High)
            {
                return;
            }

            // Get the cancel token
            var cancel = new System.Threading.CancellationTokenSource();
            taskInstance.Canceled += (s, e) =>
            {
                cancel.Cancel();
                cancel.Dispose();
            };

            // Get deferral
            var deferral = taskInstance.GetDeferral();
            try
            {
                // Update Tile with the new xml
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(TileUpdaterTask.w10TileXml);

                TileNotification tileNotification = new TileNotification(xmldoc);
                TileUpdater tileUpdator = TileUpdateManager.CreateTileUpdaterForApplication();
                tileUpdator.Update(tileNotification);
            }
            finally
            {
                deferral.Complete();
            }
        }
示例#5
0
 public void EnqueueTask(Func <Task> task)
 {
     lock (tasks)
     {
         tasks.Enqueue(task);
         cancellation?.Cancel();
     }
 }
示例#6
0
 /// <summary>
 /// Stops all active async search sessions held by this MultiProviderAsyncSearchSession.
 /// </summary>
 public void StopAllAsyncSearchSessions()
 {
     m_CancelSource?.Cancel();
     foreach (var searchSession in m_SearchSessions)
     {
         searchSession.Value.Stop();
     }
 }
示例#7
0
        private async void LifeControl_LifeChanged(object sender, LifeChangedEventArgs e)
        {
            if (!Dispatcher.HasThreadAccess)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { LifeControl_LifeChanged(sender, e); });
            }
            else
            {
                if (viewModel.CounterType != CustomCounterType.LifeHistory)
                {
                    _cancelToken?.Cancel();
                    btnCounterType.Visibility = Visibility.Visible;
                    btnCounterType.Opacity    = 1.0;
                    // imgCountertype.Source = new BitmapImage();
                    _lastCounterType      = viewModel.CounterType;
                    viewModel.CounterType = CustomCounterType.LifeHistory;
                }

                if (e.Lifechanged == int.MinValue)
                {
                    _cancelToken?.Cancel();

                    btnCounterType.Visibility = Visibility.Visible;
                    btnCounterType.Opacity    = 1.0;

                    viewModel.CounterType = _lastCounterType;
                    _cancelToken          = new System.Threading.CancellationTokenSource();

                    FadeOut(btnCounterType, _cancelToken.Token);
                    //btnCounterType.Visibility = Visibility.Collapsed;

                    //imgCountertype.Source = new BitmapImage(new Uri("ms-appx:///" + CounterTypeHelper.CounterTypeImage(viewModel.CounterType)));
                }

                _LifeHistory = e.Lifechanged;

                UpdateCustomType();
            }
        }
        /// <summary>
        /// Signals the current task to stop
        /// </summary>
        /// <param name="waitForIt">If 'true' the method will block until the current task is finished, otherwise returns immediately</param>
        public void Stop(bool waitForIt)
        {
            if (_cancellationTokenSource != null)
            {
                lock (_innerLock)
                    _cancellationTokenSource?.Cancel();
            }

            if (waitForIt) //TODO may not work
            {
                ActiveTask?.GetAwaiter().GetResult();
            }
        }
示例#9
0
        private async Task AbortGameAsync()
        {
            abortGameItem.Visibility = Visibility.Collapsed;
            newGameItem.Visibility   = Visibility.Collapsed;

            var t = gameTask;

            if (t != null)
            {
                tokenSource?.Cancel();
                handlerView.NextTurn();
                await t;
            }
        }
示例#10
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    readCancelTokenSource?.Cancel();
                    port?.DiscardInBuffer();
                    port?.DiscardOutBuffer();
                    port?.Close();
                    port?.Dispose();
                }

                disposedValue = true;
            }
        }
示例#11
0
        private void cancel_button_Click(object sender, EventArgs e)
        {
            cancel_button.Enabled = false;

            _backgroundWorkerCTS?.Cancel();
            _backgroundWorkerCTS?.Dispose();

            backgroundWorker1.CancelAsync();

            _cancelled = true;

            if (sender is string)
            {
                _exitOnComplete = true;
            }
        }
        public void MusicPlayer_PlaysMusic()
        {
            System.Diagnostics.Trace.WriteLine("Started");
            MusicPlayer p = new MusicPlayer();
            var ts = new System.Threading.CancellationTokenSource();
            p.MuteUnMute();
            Task.Factory.StartNew(p.PlayMusic, null, ts.Token);

            System.Threading.Thread.Sleep(200);
            string track1 = p.CurrentlyPlaying;
            System.Diagnostics.Trace.WriteLine("Playing 1:" + track1.ToString());
            p.PlayNext();

            Assert.IsFalse(string.IsNullOrWhiteSpace(track1));

            ts.Cancel(true);
            System.Diagnostics.Trace.WriteLine("Stopped");
        }
示例#13
0
        static void Main(string[] args)
        {
            if (!File.Exists(SettingFileName))
            {
                var settings = new Settings()
                {
                    CarName = "carName", HubName = "CentralHost", Url = "http://url", ServoPin = "7", ServoLeft = "0", ServoRight = "100", ServoStraight = "50"
                };
                using (var file = File.Create(SettingFileName))
                {
                    using (var writer = new StreamWriter(file))
                    {
                        writer.Write(JsonConvert.SerializeObject(settings));
                        writer.Flush();
                    }
                }
                return;
            }


            HubConnector    connector;
            CommandExecuter executer;

            try
            {
                using (var file = File.OpenText(SettingFileName))
                {
                    var setting = JsonConvert.DeserializeObject <Settings>(file.ReadToEnd());
                    connector = new HubConnector(setting.Url, setting.HubName, setting.CarName);
                    executer  = new CommandExecuter(setting);
                }
                connector.ConectStart().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return;
            }

            try
            {
                Console.WriteLine("Ready");

                string      ipaddress = "";
                IPHostEntry ipentry   = Dns.GetHostEntry(Dns.GetHostName());

                foreach (IPAddress ip in ipentry.AddressList)
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ipaddress = ip.ToString();
                        break;
                    }
                }

                connector.SentMessage(ipaddress);
                System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource();
                connector.GetCommand += command =>
                {
                    source?.Cancel();
                    source = new System.Threading.CancellationTokenSource();
                    connector.StartExcuting();
                    executer.Excute(command, source.Token).ContinueWith(t => connector.EndExcuting()).Start();
                };

                connector.AbortExcuting += () =>
                {
                    if (!source.IsCancellationRequested)
                    {
                        source.Cancel();
                    }
                };

                connector.Shutdown += () =>
                {
                    Console.WriteLine("Shutdown");
                };

                connector.Reboot += () =>
                {
                    Console.WriteLine("Reboot");
                };

                connector.ConnectingToClient += client => Console.WriteLine($"{client} is connected");

                connector.DisconnectingFromClient += () => Console.WriteLine("disconected");

                Console.Read();
            }
            catch (Exception ex)
            {
                connector.SentMessage(ex.ToString());
            }
            finally
            {
                connector.ConectStop().Wait();
                executer?.Dispose();
            }
        }
示例#14
0
 private void button2_Click(object sender, EventArgs e)
 {
     _token?.Cancel();
 }
            /// <summary>
            /// This is an internal method called from ReadInternal method.
            /// </summary>
            /// <param name="buffer">The byte array, passed to Read method.</param>
            /// <param name="offset">The offset in the buffer array to begin writing.</param>
            /// <param name="count">The number of bytes to read.</param>
            /// <param name="timeout">Milliseconds before a time-out occurs.</param>
            /// <param name="ct">A cancellation_token will be signaled by user cancellation.</param>
            /// <returns>
            /// The result of Task contains the length of bytes read. This may be less than count.
            /// </returns>
            private Task<int> ReadPartial(
                Windows.Storage.Streams.IBuffer buffer, 
                int offset, 
                int count,
                int timeout,
                System.Threading.CancellationToken ct
            )
            {
                // Buffer check.
                if ((int)buffer.Length < (offset + count))
                {
                    throw new ArgumentException("Capacity of buffer is not enough.");
                }

                var inputStream = this.cdcData.BulkInPipes[0].InputStream;
                var reader = new Windows.Storage.Streams.DataReader(inputStream);

                return Task.Run(async () =>
                {
                    // CancellationTokenSource to cancel tasks.
                    var cancellationTokenSource = new System.Threading.CancellationTokenSource();

                    // LoadAsync task.
                    var loadTask = reader.LoadAsync((uint)count).AsTask<uint>(cancellationTokenSource.Token);

                    // A timeout task that completes after the specified delay.
                    var timeoutTask = Task.Delay(timeout == Constants.InfiniteTimeout ? System.Threading.Timeout.Infinite : timeout, cancellationTokenSource.Token);

                    // Cancel tasks by user's cancellation.
                    bool canceledByUser = false;
                    ct.Register(()=>
                    {
                        canceledByUser = true;
                        cancellationTokenSource.Cancel();
                    });

                    // Wait tasks.
                    Task[] tasks = { loadTask, timeoutTask };
                    var signaledTask = await Task.WhenAny(tasks);

                    // Check the task status.
                    bool loadCompleted = signaledTask.Equals(loadTask) && loadTask.IsCompleted && !loadTask.IsCanceled;
                    bool isTimeout = signaledTask.Equals(timeoutTask) && timeoutTask.IsCompleted && !timeoutTask.IsCanceled;

                    // Cancel all incomplete tasks.
                    cancellationTokenSource.Cancel();

                    int loadedCount = 0;
                    if (loadCompleted)
                    {
                        loadedCount = (int)loadTask.Result;
                    }
                    else if (isTimeout)
                    {
                        // Timeout.
                        throw new System.TimeoutException("ReadPartial was timeout.");
                    }
                    else if (canceledByUser)
                    {
                        throw new OperationCanceledException("ReadPartial was canceled.");
                    }

                    if (loadedCount > 0)
                    {
                        var readBuffer = reader.ReadBuffer((uint)loadedCount);
                        System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.CopyTo(readBuffer, 0, buffer, (uint)offset, (uint)loadedCount);
                    }

                    return loadedCount;
                });
            }
示例#16
0
        public void TestNamedMetrics()
        {
            var ct = new System.Threading.CancellationTokenSource();

            var task1 = Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    Tracking.Container<CustomerAgeTracker>
                        .Where<CustomerFilter>(
                            new CustomerFilter
                            {
                                State = "MN",
                                StoreID = "334",
                                Environment_ServerName = "Server2"
                            })
                        .Increment(e => e.MiddleAgedCount, 1)
                        .Increment(e => e.ElderlyCount, 2);
                }
            }, ct.Token);

            var task2 = Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    Tracking.Container<CustomerAgeTracker>
                        .Increment(e => e.KidsCount, 2);
                }
            }, ct.Token);
                       

            System.Threading.Thread.Sleep(1000);

            ct.Cancel();

            Task.WaitAll(task1, task2);
            
        }
示例#17
0
 public static void AbortLast()
 {
     tokenSource?.Cancel();
 }
示例#18
0
        static void Main(string[] args)
        {
            "Wake up, HinayakuBot!".COut ();
            bool ShutDownFlag = false;
            List<Task> Tasks = new List<Task> ();
            var CommandContext = new CommandContext ();
            var StatusContext = new StatusContext ();
            var cts = new System.Threading.CancellationTokenSource ();
            Tasks.Add(Task.Run(() =>  StreamObservable.StreamStart(CommandContext,StatusContext),cts.Token));
            Tasks.Add(Task.Run (() => AILogic.AI (CommandContext,StatusContext),cts.Token));
            Tasks.Add (Task.Run (() => UserInterface (CommandContext),cts.Token));
            System.Threading.Thread.Yield ();
            Task.WhenAll (Tasks).ContinueWith (x => ShutDownFlag = true);
            CommandContext.GetCommand.Subscribe (x => {
                if(x.Keys.Any(y => y == Constant.Cmd)) x[Constant.Cmd].COut();
                else if(x.Keys.Any(y => y == Constant.Cmd)&& x[Constant.Cmd] == Constant.CmdEnd) ShutDownFlag = true ;
            });

            var IDs = GetIdFromXml ();
            var Token = TokenCreate (IDs);

            var stream = Token.Streaming.UserAsObservable()
                .Timeout (TimeSpan.FromSeconds (30))
                .Retry (5)
                .Catch((Exception e) => {
                    Console.WriteLine(e.Message);
                    if(e.StackTrace != null) Console.WriteLine(e.StackTrace);
                    return Observable.Never<StatusMessage>();
                })
                .Publish ();

            stream
                .OfType<StatusMessage>()
                .Where (x => !x.Status.User.ScreenName.Contains (@"hinayakuBot"))
                .Select (x => new TwString{Name = x.Status.User.ScreenName, Text = x.Status.Text, Id = x.Status.Id})
                .Subscribe (x => Console.WriteLine(x.Text));

            while(true){
                if (ShutDownFlag == true){
                    Task.Delay (TimeSpan.FromSeconds (15)).Wait ();
                    cts.Cancel ();
                    break;
                }
            }

            "All Done".COut ();
        }
示例#19
0
 public void CancelOperations()
 {
     _cancelTokenSource.Cancel();
 }
示例#20
0
        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            this._link  = txtLink.Text;
            this._start = txtFrom.Text;
            this._end   = txtTo.Text;

            bool fromToValid = (System.Text.RegularExpressions.Regex.IsMatch(_start, @"^\d+$") || _start.Equals(String.Empty)) &&
                               (System.Text.RegularExpressions.Regex.IsMatch(_end, @"^\d+$") || _end.Equals(String.Empty));

            if (String.IsNullOrWhiteSpace(_link) && fromToValid)
            {
                MessageBox.Show("Error parsing link and/or chapter range!", "", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            if (!_link.StartsWith("http"))
            {
                _link = @"http://" + _link;
            }
            if (!_link.EndsWith("/"))
            {
                _link += "/";
            }

            if (!Syousetsu.Methods.IsValidLink(_link))
            {
                MessageBox.Show("Link not valid!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            Syousetsu.Constants sc = new Syousetsu.Constants();
            sc.ChapterTitle.Add("");
            HtmlDocument toc = Syousetsu.Methods.GetTableOfContents(_link, sc.SyousetsuCookie);

            if (!Syousetsu.Methods.IsValid(toc))
            {
                MessageBox.Show("Link not valid!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }


            GetFilenameFormat();
            _row += 1;

            Label lb = new Label();

            lb.Content = Syousetsu.Methods.GetTitle(toc);
            lb.ToolTip = "Click to open folder";

            ProgressBar pb = new ProgressBar();

            pb.Maximum = (_end == String.Empty) ? Syousetsu.Methods.GetTotalChapters(toc) : Convert.ToDouble(_end);
            pb.ToolTip = "Click to stop download";
            pb.Height  = 10;

            Separator s = new Separator();

            s.Height = 5;

            _start = (_start == String.Empty) ? "1" : _start;
            _end   = pb.Maximum.ToString();

            sc.SeriesTitle     = lb.Content.ToString();
            sc.Link            = _link;
            sc.Start           = _start;
            sc.End             = _end;
            sc.CurrentFileType = _fileType;
            sc.SeriesCode      = Syousetsu.Methods.GetSeriesCode(_link);
            sc.FilenameFormat  = _format;
            Syousetsu.Methods.GetAllChapterTitles(sc, toc);

            if (chkList.IsChecked == true)
            {
                Syousetsu.Create.GenerateTableOfContents(sc, toc);
            }

            System.Threading.CancellationTokenSource ct = Syousetsu.Methods.AddDownloadJob(sc, pb);
            pb.MouseDown += (snt, evt) =>
            {
                ct.Cancel();
                pb.ToolTip = null;
            };
            lb.MouseDown += (snt, evt) =>
            {
                string path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), sc.SeriesTitle);
                if (System.IO.Directory.Exists(path))
                {
                    System.Diagnostics.Process.Start("explorer.exe", path);
                }
            };

            stackPanel1.Children.Add(lb);
            stackPanel1.Children.Add(pb);
            stackPanel1.Children.Add(s);

            _controls.Add(new Syousetsu.Controls {
                ID = _row, Label = lb, ProgressBar = pb, Separator = s
            });
        }
 private void CancelButtonClickExe()
 {
     _token?.Cancel();
 }
示例#22
0
        public async void PlayStation(Station s, Windows.UI.Xaml.Controls.MediaElement me, bool navigate = true)
        {
            if (s == null) return;

            if (!NetworkCostController.IsConnectedToInternet) //makes sure Hanasu is connected to the internet.
            {
                Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>()
                    .ShowMessage(
                        LocalizationManager.GetLocalizedValue("InternetConnectionHeader"),
                        LocalizationManager.GetLocalizedValue("NoInternetConnectionMsg"));
                return;
            }

            if (NetworkCostController.CurrentNetworkingBehavior == NetworkingBehavior.Opt_In) //if the user is roaming and/or over the data limit, notify them
            {
                Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>()
                    .ShowMessage(
                        LocalizationManager.GetLocalizedValue("DataConstraintsHeader"),
                        LocalizationManager.GetLocalizedValue("StreamingDisabled2Msg"));

                return;
            }

            // Reset things things are ready to be played.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                {
                    SetMediaElement(ref me);

                    CurrentStation = s;
                    CurrentStationSongData = null;
                    CurrentStationStreamedUri = null;
                });

            StorageFile albumFile = await GetStationAlbumFromCache(); //Grab the current station's logo from the cache.

            if (albumFile != null)
                MediaControl.AlbumArt = new Uri("ms-appdata:///local/Hanasu/" + albumFile.DisplayName); //Set the logo in the media control.
            MediaControl.ArtistName = CurrentStation.Title; //set the station's name
            MediaControl.IsPlaying = true;

            try
            {

                if (me.CurrentState == MediaElementState.Playing || me.CurrentState == MediaElementState.Opening || me.CurrentState == MediaElementState.Buffering)
                {
                    me.Pause();
                    await Task.Delay(1000);
                    me.Stop();
                }

                Uri finalUri = new Uri(s.StreamUrl, UriKind.Absolute);

                if (await Hanasu.Core.Preprocessor.PreprocessorService.CheckIfPreprocessingIsNeeded(finalUri, s.PreprocessorFormat))
                    finalUri = await Hanasu.Core.Preprocessor.PreprocessorService.GetProcessor(finalUri, s.PreprocessorFormat).Process(finalUri);

                CurrentStationStreamedUri = finalUri;

                //if (CurrentStation.ServerType.ToLower() == "shoutcast")
                //{
                //    var str = await ShoutcastService.GetShoutcastStream(finalUri);
                //    mediaElement.SetSource(str, str.Content_Type);

                //    mediaElement.Play();
                //}
                //else
                //{

                //finalUri = new Uri(finalUri.ToString() + ";stream.nsv", UriKind.Absolute);

                try
                {
                    System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();

                    var openTask = mediaElement.OpenAsync(finalUri, cts.Token);
                    var timeoutTask = Task.Delay(10000); //Wait for a connection for 10 seconds.

                    var successful = await Task.WhenAny(openTask, timeoutTask);

                    if (successful == timeoutTask)
                    {
                        //timeout. inform the user and back out.

                        IsPlaying = false;

                        Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>()
                            .ShowMessage(
                                 LocalizationManager.GetLocalizedValue("StreamingErrorHeader"),
                                 LocalizationManager.GetLocalizedValue("StreamingConnectionTimeoutMsg"));

                        cts.Cancel();
                        cts.Dispose();

                        ResetStationInfo();

                        return;
                    }
                }
                catch (Exception ex)
                {
                    if (ex is TaskCanceledException) return;

                    throw ex;
                }

                if (navigate && IsPlaying)
                    NavigateToNowPlayingPage(finalUri);

                try
                {
                    if (!PlayToController.IsConnectedViaPlayTo)
                    {
                        var playTask = mediaElement.PlayAsync(System.Threading.CancellationToken.None);
                        IsPlaying = true;
                        await playTask;
                    }
                    else
                        IsPlaying = true;
                }
                catch (Exception ex)
                {
                    if (ex is TaskCanceledException) return;

                    throw ex;
                }

                //}
            }
            catch (Exception ex)
            {
                if (mediaElement.CurrentState == MediaElementState.Playing || mediaElement.CurrentState == MediaElementState.Opening) return; //Ignorable error. Probably nothing.

                IsPlaying = false;

                Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>()
                    .ShowMessage(
                        LocalizationManager.GetLocalizedValue("StreamingErrorHeader"),
                        LocalizationManager.GetLocalizedValue("StreamingErrorMsg"));
            }

        }
示例#23
0
        Run()
        {
            Log.Detail("Running build");

            // TODO: should the rank collections be sorted, so that modules with fewest dependencies are first?

            var graph           = Graph.Instance;
            var metaDataType    = graph.BuildModeMetaData.GetType();
            var useEvaluation   = CheckIfModulesNeedRebuilding(metaDataType);
            var explainRebuild  = CommandLineProcessor.Evaluate(new Options.ExplainBuildReason());
            var immediateOutput = CommandLineProcessor.Evaluate(new Options.ImmediateOutput());

            ExecutePreBuild(metaDataType);

            if (!System.IO.Directory.Exists(graph.BuildRoot))
            {
                System.IO.Directory.CreateDirectory(graph.BuildRoot);
            }

            var threadCount = CommandLineProcessor.Evaluate(new Options.MultiThreaded());

            if (0 == threadCount)
            {
                threadCount = System.Environment.ProcessorCount;
            }

            System.Exception abortException = null;
            if (threadCount > 1)
            {
                var cancellationSource = new System.Threading.CancellationTokenSource();
                var cancellationToken  = cancellationSource.Token;

                // LongRunning is absolutely necessary in order to achieve paralleism
                var creationOpts     = System.Threading.Tasks.TaskCreationOptions.LongRunning;
                var continuationOpts = System.Threading.Tasks.TaskContinuationOptions.LongRunning;

                var scheduler = new LimitedConcurrencyLevelTaskScheduler(threadCount);

                var factory = new System.Threading.Tasks.TaskFactory(
                    cancellationToken,
                    creationOpts,
                    continuationOpts,
                    scheduler);

                var tasks = new Array <System.Threading.Tasks.Task>();
                foreach (var rank in graph.Reverse())
                {
                    foreach (var module in rank)
                    {
                        var context = new ExecutionContext(useEvaluation, explainRebuild, immediateOutput);
                        var task    = factory.StartNew(() =>
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                return;
                            }
                            var depTasks = new Array <System.Threading.Tasks.Task>();
                            foreach (var dep in module.Dependents)
                            {
                                if (null == dep.ExecutionTask)
                                {
                                    continue;
                                }
                                depTasks.Add(dep.ExecutionTask);
                            }
                            foreach (var dep in module.Requirements)
                            {
                                if (null == dep.ExecutionTask)
                                {
                                    continue;
                                }
                                depTasks.Add(dep.ExecutionTask);
                            }
                            System.Threading.Tasks.Task.WaitAll(depTasks.ToArray());
                            if (cancellationToken.IsCancellationRequested)
                            {
                                return;
                            }

                            try
                            {
                                (module as IModuleExecution).Execute(context);
                            }
                            catch (Exception ex)
                            {
                                abortException = ex;
                                cancellationSource.Cancel();
                            }
                            finally
                            {
                                if (context.OutputStringBuilder != null && context.OutputStringBuilder.Length > 0)
                                {
                                    Log.Info(context.OutputStringBuilder.ToString());
                                }
                                if (context.ErrorStringBuilder != null && context.ErrorStringBuilder.Length > 0)
                                {
                                    Log.Info(context.ErrorStringBuilder.ToString());
                                }
                            }
                        });
                        tasks.Add(task);
                        module.ExecutionTask = task;
                    }
                }
                try
                {
                    System.Threading.Tasks.Task.WaitAll(tasks.ToArray());
                }
                catch (System.AggregateException exception)
                {
                    if (!(exception.InnerException is System.Threading.Tasks.TaskCanceledException))
                    {
                        throw new Exception(exception, "Error during threaded build");
                    }
                }
            }
            else
            {
                foreach (var rank in graph.Reverse())
                {
                    if (null != abortException)
                    {
                        break;
                    }
                    foreach (IModuleExecution module in rank)
                    {
                        var context = new ExecutionContext(useEvaluation, explainRebuild, immediateOutput);
                        try
                        {
                            module.Execute(context);
                        }
                        catch (Exception ex)
                        {
                            abortException = ex;
                            break;
                        }
                        finally
                        {
                            if (context.OutputStringBuilder != null && context.OutputStringBuilder.Length > 0)
                            {
                                Log.Info(context.OutputStringBuilder.ToString());
                            }
                            if (context.ErrorStringBuilder != null && context.ErrorStringBuilder.Length > 0)
                            {
                                Log.Info(context.ErrorStringBuilder.ToString());
                            }
                        }
                    }
                }
            }

            if (null != abortException)
            {
                throw new Exception(abortException, "Error during {0}threaded build", (threadCount > 1) ? string.Empty : "non-");
            }

            ExecutePostBuild(metaDataType);
        }
示例#24
0
        public void TestPerformaceMetrics()
        {
            var ct = new System.Threading.CancellationTokenSource();

            var task1 = Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    var sw = Stopwatch.StartNew();

                    System.Threading.Thread.Sleep(Convert.ToInt32((new Random()).NextDouble() * 100) + 5);

                    sw.Stop();

                    Tracking.Container<PerformanceTracker>
                        .Where<EnvironmentFilter>(
                            new EnvironmentFilter
                            {
                                ServerName = "Server2"
                            })
                        .Increment(e => e.NumberOfCalls, 1)
                        .Increment(e => e.TotalResponseTimeInMilliseconds, sw);

                    sw.Reset();
                    sw.Start();
                    System.Threading.Thread.Sleep(Convert.ToInt32((new Random()).NextDouble() * 100) + 5);
                    sw.Stop();

                    Tracking.Container<PerformanceTracker>
                        .Where<EnvironmentFilter>(
                            new EnvironmentFilter
                            {
                                ServerName = "Server1"
                            })
                        .Increment(e => e.NumberOfCalls, 1)
                        .Increment(e => e.TotalResponseTimeInMilliseconds, sw);
                }
            }, ct.Token);

            var task2 = Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    var sw = Stopwatch.StartNew();

                    System.Threading.Thread.Sleep(Convert.ToInt32((new Random()).NextDouble() * 100) + 5);

                    sw.Stop();

                    Tracking.Container<PerformanceTracker>
                        .Increment(e => e.NumberOfCalls, 1)
                        .Increment(e => e.TotalResponseTimeInMilliseconds, sw);
                }
            }, ct.Token);


            System.Threading.Thread.Sleep(1000);

            ct.Cancel();

            Task.WaitAll(task1, task2);

        }
示例#25
0
        static void Main(string[] args)
        {
            Console.WriteLine("[Demo] Start demo msmq_receiver");
            //KubeMQ address is environment var "KubeMQServerAddress" GRPC port
            Console.WriteLine($"[Demo] KUBEMQ GRPC address:{Environment.GetEnvironmentVariable("KubeMQServerAddress")}");
            Console.WriteLine($"[Demo] ClientID:{ClientID}");
            Console.WriteLine($"[Demo] Publish rates channel PUBCHANNEL:{PubChannel}");
            Console.WriteLine($"[Demo] Command channel CMDChannel:{CMDChannel}");


            Console.WriteLine($"[Demo] KubeMQ MSMQ SDK message timeout KUBEMQTIMEOUT:{Environment.GetEnvironmentVariable("KUBEMQTIMEOUT")}");
            Console.WriteLine($"[Demo] KubeMQ MSMQ SDK message channel:{Environment.GetEnvironmentVariable("KUBEMQSCHANNEL")}");



            Console.WriteLine($"[Demo] init KubeMQ MessageQueue RateMQ:{RateMQ}");
            MessageQueue receiveMQ = new MessageQueue(RateMQ);

            Console.WriteLine($"[Demo] init KubeMQ MessageQueue CMDMQs:{CMDMQ}");
            MessageQueue sendMQ = new MessageQueue(CMDMQ);


            System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource();
            System.Threading.CancellationToken       token  = source.Token;



            /// Init a new sender channel on the KubeMQ to publish received rates

            KubeMQ.SDK.csharp.Events.Channel channel = new KubeMQ.SDK.csharp.Events.Channel(new KubeMQ.SDK.csharp.Events.ChannelParameters
            {
                ChannelName = PubChannel,
                ClientID    = ClientID,
                Store       = true
            });

            Console.WriteLine($"[Demo][DequeueAndEventPub] init KubeMQ publish persistence channel  PubChannel:{PubChannel}");

            //start a task for dequeue messages from MSMSQ using KubeMQ MSMQ SDK

            Task.Run((Func <Task>)(async() =>
            {
                //DequeueAndEventPub task implementing KubeMQ.MSMQ.SDK will request a Dequeue from KubeMQ MSMQ Worker publish the message to persistent KubeMQ channel.

                await DequeueAndEventPub(receiveMQ, channel);
            }), token);


            //start a task for enqueue MSMSQ messages using KubeMQ MSMQ SDK
            Task.Run((Func <Task>)(async() =>
            {
                await CommandHanleAndEnqueue(sendMQ);
            }), token);


            Console.WriteLine("[Demo] press Ctrl+c to stop");

            System.Threading.AutoResetEvent waitHandle = new System.Threading.AutoResetEvent(false);
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
            {
                Console.WriteLine($"[Demo] finish Demo");
                source.Cancel();
                e.Cancel = true;
                waitHandle.Set();
            };

            waitHandle.WaitOne();
        }
示例#26
0
 public void Stop()
 {
     cancellation?.Cancel();
     timer.Stop();
     Model.IsIconVisible = false;
 }
示例#27
0
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            WebAppAndElmAppConfig webAppAndElmAppConfig,
            Func <DateTimeOffset> getDateTimeOffset,
            IHostApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            if (webAppAndElmAppConfig == null)
            {
                throw new Exception("Missing reference to the web app config.");
            }

            var applicationStoppingCancellationTokenSource = new System.Threading.CancellationTokenSource();

            appLifetime.ApplicationStopping.Register(() =>
            {
                applicationStoppingCancellationTokenSource.Cancel();
                _logger?.LogInformation("Public app noticed ApplicationStopping.");
            });

            var nextHttpRequestIndex = 0;

            if (webAppAndElmAppConfig.WebAppConfiguration?.letsEncryptOptions != null)
            {
                app.UseFluffySpoonLetsEncryptChallengeApprovalMiddleware();
            }

            var createVolatileHostAttempts = 0;

            var volatileHosts = new ConcurrentDictionary <string, VolatileHost>();

            var appTaskCompleteHttpResponse = new ConcurrentDictionary <string, InterfaceToHost.HttpResponse>();

            System.Threading.Timer notifyTimeHasArrivedTimer  = null;
            DateTimeOffset?        lastAppEventTimeHasArrived = null;

            InterfaceToHost.NotifyWhenArrivedAtTimeRequestStructure nextTimeToNotify = null;
            var nextTimeToNotifyLock = new object();

            InterfaceToHost.Result <InterfaceToHost.TaskResult.RequestToVolatileHostError, InterfaceToHost.TaskResult.RequestToVolatileHostComplete>
            performProcessTaskRequestToVolatileHost(
                InterfaceToHost.Task.RequestToVolatileHostStructure requestToVolatileHost)
            {
                if (!volatileHosts.TryGetValue(requestToVolatileHost.hostId, out var volatileHost))
                {
                    return(new InterfaceToHost.Result <InterfaceToHost.TaskResult.RequestToVolatileHostError, InterfaceToHost.TaskResult.RequestToVolatileHostComplete>
                    {
                        Err = new InterfaceToHost.TaskResult.RequestToVolatileHostError
                        {
                            HostNotFound = new object(),
                        }
                    });
                }

                var stopwatch = System.Diagnostics.Stopwatch.StartNew();

                var fromVolatileHostResult = volatileHost.ProcessRequest(requestToVolatileHost.request);

                stopwatch.Stop();

                return(new InterfaceToHost.Result <InterfaceToHost.TaskResult.RequestToVolatileHostError, InterfaceToHost.TaskResult.RequestToVolatileHostComplete>
                {
                    Ok = new InterfaceToHost.TaskResult.RequestToVolatileHostComplete
                    {
                        exceptionToString = fromVolatileHostResult.Exception?.ToString(),
                        returnValueToString = fromVolatileHostResult.ReturnValue?.ToString(),
                        durationInMilliseconds = stopwatch.ElapsedMilliseconds,
                    }
                });
            }

            InterfaceToHost.TaskResult performProcessTask(InterfaceToHost.Task task)
            {
                if (task?.CreateVolatileHost != null)
                {
                    try
                    {
                        var volatileHost = new VolatileHost(BlobLibrary.GetBlobWithSHA256, task?.CreateVolatileHost.script);

                        var volatileHostId = System.Threading.Interlocked.Increment(ref createVolatileHostAttempts).ToString();

                        volatileHosts[volatileHostId] = volatileHost;

                        return(new InterfaceToHost.TaskResult
                        {
                            CreateVolatileHostResponse = new InterfaceToHost.Result <InterfaceToHost.TaskResult.CreateVolatileHostErrorStructure, InterfaceToHost.TaskResult.CreateVolatileHostComplete>
                            {
                                Ok = new InterfaceToHost.TaskResult.CreateVolatileHostComplete
                                {
                                    hostId = volatileHostId,
                                },
                            },
                        });
                    }
                    catch (Exception createVolatileHostException)
                    {
                        return(new InterfaceToHost.TaskResult
                        {
                            CreateVolatileHostResponse = new InterfaceToHost.Result <InterfaceToHost.TaskResult.CreateVolatileHostErrorStructure, InterfaceToHost.TaskResult.CreateVolatileHostComplete>
                            {
                                Err = new InterfaceToHost.TaskResult.CreateVolatileHostErrorStructure
                                {
                                    exceptionToString = createVolatileHostException.ToString(),
                                },
                            },
                        });
                    }
                }

                if (task?.ReleaseVolatileHost != null)
                {
                    volatileHosts.TryRemove(task?.ReleaseVolatileHost.hostId, out var volatileHost);

                    return(new InterfaceToHost.TaskResult
                    {
                        CompleteWithoutResult = new object(),
                    });
                }

                if (task?.RequestToVolatileHost != null)
                {
                    return(new InterfaceToHost.TaskResult
                    {
                        RequestToVolatileHostResponse = performProcessTaskRequestToVolatileHost(task?.RequestToVolatileHost),
                    });
                }

                throw new NotImplementedException("Unexpected task structure.");
            }

            void performProcessTaskAndFeedbackEvent(InterfaceToHost.StartTask taskWithId)
            {
                var taskResult = performProcessTask(taskWithId.task);

                var interfaceEvent = new InterfaceToHost.AppEventStructure
                {
                    TaskCompleteEvent = new InterfaceToHost.ResultFromTaskWithId
                    {
                        taskId     = taskWithId.taskId,
                        taskResult = taskResult,
                    }
                };

                processEventAndResultingRequests(interfaceEvent);
            }

            void processEventAndResultingRequests(InterfaceToHost.AppEventStructure interfaceEvent)
            {
                var prepareProcessEvent = prepareProcessEventAndResultingRequests(interfaceEvent);

                prepareProcessEvent.processEventAndResultingRequests();
            }

            (string serializedInterfaceEvent, Action processEventAndResultingRequests) prepareProcessEventAndResultingRequests(
                InterfaceToHost.AppEventStructure interfaceEvent)
            {
                var serializedInterfaceEvent = Newtonsoft.Json.JsonConvert.SerializeObject(interfaceEvent, jsonSerializerSettings);

                var processEvent = new Action(() =>
                {
                    if (applicationStoppingCancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }

                    string serializedResponse = null;

                    try
                    {
                        serializedResponse = webAppAndElmAppConfig.ProcessEventInElmApp(serializedInterfaceEvent);
                    }
                    catch (Exception) when(applicationStoppingCancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }

                    InterfaceToHost.ResponseOverSerialInterface structuredResponse = null;

                    try
                    {
                        structuredResponse =
                            Newtonsoft.Json.JsonConvert.DeserializeObject <InterfaceToHost.ResponseOverSerialInterface>(
                                serializedResponse);
                    }
                    catch (Exception parseException)
                    {
                        throw new Exception(
                            "Failed to parse event response from app. Looks like the loaded elm app is not compatible with the interface.\nResponse from app follows:\n" + serializedResponse,
                            parseException);
                    }

                    if (structuredResponse?.DecodeEventSuccess == null)
                    {
                        throw new Exception("Hosted app failed to decode the event: " + structuredResponse.DecodeEventError);
                    }

                    if (structuredResponse.DecodeEventSuccess.notifyWhenArrivedAtTime != null)
                    {
                        System.Threading.Tasks.Task.Run(() =>
                        {
                            lock (nextTimeToNotifyLock)
                            {
                                nextTimeToNotify = structuredResponse.DecodeEventSuccess.notifyWhenArrivedAtTime;
                            }
                        });
                    }

                    foreach (var startTask in structuredResponse.DecodeEventSuccess.startTasks)
                    {
                        System.Threading.Tasks.Task.Run(() => performProcessTaskAndFeedbackEvent(startTask));
                    }

                    foreach (var completeHttpResponse in structuredResponse.DecodeEventSuccess.completeHttpResponses)
                    {
                        appTaskCompleteHttpResponse[completeHttpResponse.httpRequestId] =
                            completeHttpResponse.response;
                    }
                });

                return(serializedInterfaceEvent, processEvent);
            }

            void processEventTimeHasArrived()
            {
                var currentTime = getDateTimeOffset();

                lastAppEventTimeHasArrived = currentTime;

                processEventAndResultingRequests(new InterfaceToHost.AppEventStructure
                {
                    ArrivedAtTimeEvent = new InterfaceToHost.ArrivedAtTimeEventStructure
                    {
                        posixTimeMilli = currentTime.ToUnixTimeMilliseconds()
                    }
                });
            }

            notifyTimeHasArrivedTimer = new System.Threading.Timer(
                callback: _ =>
            {
                if (applicationStoppingCancellationTokenSource.IsCancellationRequested)
                {
                    notifyTimeHasArrivedTimer?.Dispose();
                    return;
                }

                lock (nextTimeToNotifyLock)
                {
                    if (applicationStoppingCancellationTokenSource.IsCancellationRequested)
                    {
                        notifyTimeHasArrivedTimer?.Dispose();
                        return;
                    }

                    var localNextTimeToNotify = nextTimeToNotify;

                    if (localNextTimeToNotify != null && localNextTimeToNotify.posixTimeMilli <= getDateTimeOffset().ToUnixTimeMilliseconds())
                    {
                        nextTimeToNotify = null;
                        processEventTimeHasArrived();
                        return;
                    }
                }

                if (lastAppEventTimeHasArrived.HasValue
                        ?
                    notifyTimeHasArrivedMaximumDistance <= (getDateTimeOffset() - lastAppEventTimeHasArrived.Value)
                        :
                    true)
                {
                    processEventTimeHasArrived();
                }
            },
                state: null,
                dueTime: TimeSpan.Zero,
                period: TimeSpan.FromMilliseconds(10));

            processEventTimeHasArrived();

            app
            .Use(async(context, next) => await Asp.MiddlewareFromWebAppConfig(webAppAndElmAppConfig.WebAppConfiguration, context, next))
            .Run(async(context) =>
            {
                var currentDateTime  = getDateTimeOffset();
                var timeMilli        = currentDateTime.ToUnixTimeMilliseconds();
                var httpRequestIndex = System.Threading.Interlocked.Increment(ref nextHttpRequestIndex);

                var httpRequestId = timeMilli.ToString() + "-" + httpRequestIndex.ToString();

                var httpRequestEvent =
                    await AsPersistentProcessInterfaceHttpRequestEvent(context, httpRequestId, currentDateTime);

                var httpRequestInterfaceEvent = new InterfaceToHost.AppEventStructure
                {
                    HttpRequestEvent = httpRequestEvent,
                };

                var preparedProcessEvent = prepareProcessEventAndResultingRequests(httpRequestInterfaceEvent);

                if (webAppAndElmAppConfig.WebAppConfiguration?.httpRequestEventSizeLimit < preparedProcessEvent.serializedInterfaceEvent?.Length)
                {
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                    await context.Response.WriteAsync("Request is too large.");
                    return;
                }

                preparedProcessEvent.processEventAndResultingRequests();

                var waitForHttpResponseClock = System.Diagnostics.Stopwatch.StartNew();

                while (true)
                {
                    if (appTaskCompleteHttpResponse.TryRemove(httpRequestId, out var httpResponse))
                    {
                        var headerContentType =
                            httpResponse.headersToAdd
                            ?.FirstOrDefault(header => header.name?.ToLowerInvariant() == "content-type")
                            ?.values?.FirstOrDefault();

                        context.Response.StatusCode = httpResponse.statusCode;

                        foreach (var headerToAdd in (httpResponse.headersToAdd).EmptyIfNull())
                        {
                            context.Response.Headers[headerToAdd.name] = new Microsoft.Extensions.Primitives.StringValues(headerToAdd.values);
                        }

                        if (headerContentType != null)
                        {
                            context.Response.ContentType = headerContentType;
                        }

                        byte[] contentAsByteArray = null;

                        if (httpResponse?.bodyAsBase64 != null)
                        {
                            var buffer = new byte[httpResponse.bodyAsBase64.Length * 3 / 4];

                            if (!Convert.TryFromBase64String(httpResponse.bodyAsBase64, buffer, out var bytesWritten))
                            {
                                throw new FormatException(
                                    "Failed to convert from base64. bytesWritten=" + bytesWritten +
                                    ", input.length=" + httpResponse.bodyAsBase64.Length + ", input:\n" +
                                    httpResponse.bodyAsBase64);
                            }

                            contentAsByteArray = buffer.AsSpan(0, bytesWritten).ToArray();
                        }

                        context.Response.ContentLength = contentAsByteArray?.Length ?? 0;

                        if (contentAsByteArray != null)
                        {
                            await context.Response.Body.WriteAsync(contentAsByteArray);
                        }

                        break;
                    }

                    if (60 <= waitForHttpResponseClock.Elapsed.TotalSeconds)
                    {
                        throw new TimeoutException(
                            "The app did not return a HTTP response within " +
                            (int)waitForHttpResponseClock.Elapsed.TotalSeconds +
                            " seconds.");
                    }

                    System.Threading.Thread.Sleep(100);
                }
            });
        }
示例#28
0
 private void StopFinding()
 {
     cts.Cancel();
 }
 // Summary:
 //     Upload files by output stream.
 //
 // Parameters:
 //  sourceFolderId:
 //      The id of the place you want to upload.
 //
 //  fileName:
 //      The name you want to use after upload.
 //
 // Returns:
 //     The StorageFolder where you downloaded folder.
 public async Task<bool> UploadFileStreamAsync(string folderIdToStore, string fileName, Stream outstream)
 {
     //ProgressBar progressBar = new ProgressBar();
     //progressBar.Value = 0;
     //var progressHandler = new Progress<LiveOperationProgress>(
     //    (progress) => { progressBar.Value = progress.ProgressPercentage; });
     System.Threading.CancellationTokenSource ctsUpload = new System.Threading.CancellationTokenSource();
     try
     {
         //LiveOperationResult result = await this.LiveClient
         //    .UploadAsync(folderIdToStore, fileName, outstream, OverwriteOption.Overwrite, ctsUpload.Token, progressHandler);
         LiveOperationResult result = await this.LiveClient.BackgroundUploadAsync(folderIdToStore, fileName, outstream.AsInputStream(), OverwriteOption.Overwrite);
     }
     catch
     {
         ctsUpload.Cancel();
         throw new ShareException(fileName, ShareException.ShareType.UPLOAD);
     }
     return true;
 }
示例#30
0
        /// <summary>
        /// Get results from paged query for NuGet v3
        /// </summary>
        /// <typeparam name="B">Response body type</typeparam>
        /// <typeparam name="R">Result type</typeparam>
        /// <param name="request">Current request</param>
        /// <param name="getTotalResultsCountFromResponse">Delegate to get total result count from first response. Return 0 or a negative number to indicate failure.</param>
        /// <param name="getResultsFromResponse">Delegate to get results from a response body.</param>
        /// <param name="getPackageQuery">Delegate to get the next query, skipping a given number of results.</param>
        /// <param name="parseResponseBody">Delegate to parse the response string body to a response object body.</param>
        /// <returns>All results.</returns>
        public static IEnumerable <R> GetResults <B, R>(RequestWrapper request, Func <B, long> getTotalResultsCountFromResponse, Func <B, IEnumerable <IEnumerable <R> > > getResultsFromResponse, Func <long, string> getNextResponseQuery, Func <string, B> parseResponseBody, int pageCount)
        {
            ProgressTracker progressTracker        = new ProgressTracker(ProgressTracker.GetRandomId(), 0, 100);
            int             childProgressTrackerId = request.StartProgress(progressTracker.ProgressID, Resources.Messages.NuGetServerReadStarted);
            long            total                   = -1;
            long            resultCount             = 0;
            bool            successful              = true;
            bool            trackIndividualProgress = false;
            TaskGroup <IEnumerable <IEnumerable <R> > > taskGroup = new TaskGroup <IEnumerable <IEnumerable <R> > >();

            System.Threading.CancellationTokenSource cancelToken = new System.Threading.CancellationTokenSource();
            string query   = getNextResponseQuery(resultCount);
            string content = new StreamReader(NuGetClient.DownloadDataToStream(query, request)).ReadToEnd();

            B response = parseResponseBody(content);

            total = getTotalResultsCountFromResponse(response);
            if (total < 0)
            {
                total = -2;
                request.Warning(Messages.FailedToParseTotalHitsCount, query);
                successful = false;
            }
            else
            {
                request.Progress(childProgressTrackerId, 0, String.Format(CultureInfo.CurrentCulture, Resources.Messages.NuGetServerReadProgress, resultCount, total));
                // When the result count is low enough, track individual results. Otherwise, track by page.
                trackIndividualProgress = total <= (pageCount * 2);
                taskGroup.Add(Task.Factory.StartNew <IEnumerable <IEnumerable <R> > >(() => { return(getResultsFromResponse(response)); }, cancelToken.Token));
            }

            if (total >= 0)
            {
                long numberOfPages = total / pageCount + (total % pageCount == 0 ? 0 : 1);
                long pageSkipCount = 0;
                for (long pageNum = 1; pageNum < numberOfPages; pageNum++)
                {
                    pageSkipCount += pageCount;
                    string pageQuery = getNextResponseQuery(pageSkipCount);
                    taskGroup.Add(Task.Factory.StartNew <IEnumerable <IEnumerable <R> > >((q) =>
                    {
                        string pageContent = new StreamReader(NuGetClient.DownloadDataToStream((string)q, request)).ReadToEnd();
                        B pageResponse     = parseResponseBody(pageContent);
                        return(getResultsFromResponse(pageResponse));
                    }, pageQuery, cancelToken.Token));
                }
            }

            while (taskGroup.HasAny)
            {
                if (request.IsCanceled())
                {
                    cancelToken.Cancel();
                    successful = false;
                    break;
                }

                IEnumerable <IEnumerable <R> > resultCollections = taskGroup.WaitAny();
                foreach (IEnumerable <R> resultCollection in resultCollections)
                {
                    resultCount++;
                    // If trackIndividualProgress == false, this progress will be reported at the end
                    if (trackIndividualProgress)
                    {
                        // Report an individual package is done processing
                        request.Progress(childProgressTrackerId, progressTracker.ConvertPercentToProgress(((double)resultCount) / total),
                                         String.Format(CultureInfo.CurrentCulture, Resources.Messages.NuGetServerReadProgress, resultCount, total));
                    }

                    foreach (R result in resultCollection)
                    {
                        yield return(result);
                    }
                }

                if (!trackIndividualProgress)
                {
                    // Report that this page is done processing
                    request.Progress(childProgressTrackerId, progressTracker.ConvertPercentToProgress(((double)resultCount) / total),
                                     String.Format(CultureInfo.CurrentCulture, Resources.Messages.NuGetServerReadProgress, resultCount, total));
                }
            }

            request.CompleteProgress(childProgressTrackerId, successful);
            request.CompleteProgress(progressTracker.ProgressID, successful);
        }
示例#31
0
        static void Main(string[] args)
        {
            for (int i = 0; i < 20; i++)
            {

                var rand = new Random();
                LockHelper lockhelp = new MonitorLockHelper();

                var sw = new System.Diagnostics.Stopwatch();

                int[] range = Enumerable.Range(1, (int)Math.Pow(2.0, 23)).ToArray();
                //sw.Restart();
                //var btTestNoLookupSTRand = new btree(lockhelp);
                //RandomRangeInsert(btTestNoLookupSTRand, range, sw, true);
                //sw.Stop();
                //Console.WriteLine("Random insert single threaded time {0}ms for {1} nodes", sw.Elapsed.TotalMilliseconds, (int)Math.Pow(2.0, 24));

                //sw.Restart();
                //var btTestNoLookupRand = new btree(lockhelp);
                //RandomRangeInsert(btTestNoLookupRand, range, sw);
                //Task.WaitAll(wh.ToArray());
                //sw.Stop();
                //wh.Clear();
                //Console.WriteLine("Random insert multi threaded time {0}ms for {1} nodes", sw.Elapsed.TotalMilliseconds, (int)Math.Pow(2.0, 24));

                //sw.Restart();
                //var btTestNoLookupsST = new btree(lockhelp);
                //BalancedRangeInsert(btTestNoLookupsST, range, sw, true);
                //sw.Stop();
                //Console.WriteLine("Balanced insert single threaded time {0}ms for {1} nodes", sw.Elapsed.TotalMilliseconds, (int)Math.Pow(2.0, 24));

                //sw.Restart();
                //var btTestNoLookups = new btree(lockhelp);
                //BalancedRangeInsert(btTestNoLookups, range, sw);
                //Task.WaitAll(wh.ToArray());
                //sw.Stop();
                //wh.Clear();
                //Console.WriteLine("Balanced insert multi threaded time {0}ms for {1} nodes", sw.Elapsed.TotalMilliseconds, (int)Math.Pow(2.0, 24));

                sw.Restart();
                var bttest = new btree(lockhelp);
                BalancedRangeInsert(bttest, range, sw);

                var cts = new System.Threading.CancellationTokenSource();
                var t = new Task(() =>
                {
                    bool contains = true;
                    while (!cts.IsCancellationRequested)
                    {
                        contains &= bttest.Contains(rand.Next(1, (int)Math.Pow(2.0, 22)));
                        System.Threading.Thread.Sleep(1);
                    }
                }, cts.Token);

                var t2 = new Task(() =>
                {
                    while (!cts.IsCancellationRequested)
                    {
                        bttest.Remove(rand.Next(1, (int)Math.Pow(2.0, 22)));
                        System.Threading.Thread.Sleep(1);
                    }
                }, cts.Token);
                t2.Start();
                Task.WaitAll(wh.ToArray());
                sw.Stop();
                cts.Cancel();
                Console.WriteLine("Balanced insert multi threaded, w/ lookup and removal time: {0}", sw.Elapsed.TotalMilliseconds);
            }
            Console.ReadLine();
        }
示例#32
0
    public void Handshake()
    {
      received = 0;
      source = new System.Threading.CancellationTokenSource();
      cancel = source.Token;

      using (var client = new System.Net.Sockets.TcpClient())
      {
        client.Connect(Environment.MachineName, port);
        using (var stream = client.GetStream())
        {
          var handshake = Encoding.UTF8.GetBytes("GO");
          stream.Write(handshake, 0, handshake.Length);

          Task.Run(() => ack_nack(stream));

          do
          {
            int read = stream.Read(buffer, 0, buffer_size);
            //System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
            //at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
            if (read == 0) break;
            var block = Encoding.UTF8.GetString(buffer, 0, read);
            foreach (var msg in block.Split('\n'))
            {
              Console.WriteLine($"Received:[{msg}]");
              ++received;
            }
          } while (true);
          source.Cancel();
        }
      }
    }
示例#33
0
        //private List<Dto> GetData()
        //{
        //    var result = new List<Dto>();
        //    for (int i = 0; i < 5; i++)
        //    {
        //        if (_isCancel)
        //        {
        //            return null;
        //        }
        //        System.Threading.Thread.Sleep(1000);
        //        result.Add(new Dto ( i.ToString(),  "Name" + i ));
        //    }


        //    return result;

        //}

        private void CancelButton_Click(object sender, EventArgs e)
        {
            _token?.Cancel();
            //_isCancel = true;
            //_dataBase.Cancel();
        }
示例#34
0
        public void TestIncrement()
        {
            var ct = new System.Threading.CancellationTokenSource();
           
            var task1 = Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    //Graphene.Tracking.Container<PatientLinkValidationTracker>.IncrementBy(1);
                    Graphene.Tracking.Container<CustomerVisitTracker>
                        .Where<CustomerFilter>(
                            new CustomerFilter
                            {
                                State = "CA",
                                StoreID = "3234",
                                Environment_ServerName = "Server1"
                            }).IncrementBy(1);
                    _task1Count++;
                   // System.Threading.Thread.Sleep(500);
                }
            }, ct.Token);

            var task2 = Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    Graphene.Tracking.Container<CustomerPurchaseTracker>
                        .Where<CustomerFilter>(
                            new CustomerFilter
                            {
                                State = "MN",
                                StoreID = "334",
                                Environment_ServerName = "Server2"
                            }).IncrementBy(1);
                    _task2Count++;
                   // System.Threading.Thread.Sleep(100);
                }
            }, ct.Token);

            var task3 = Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    Tracking.Container<CustomerVisitTracker>.IncrementBy(3);
                    _task3Count++;
                    //System.Threading.Thread.Sleep(500);
                }
            }, ct.Token);

            System.Threading.Thread.Sleep(1000);            

            ct.Cancel();

            Task.WaitAll(task1, task2, task3);
        }
 private async void SimilarTasksWithWhenAny(object sender, RoutedEventArgs e)
 {
     ResultTextBlock.Text = "Testing... Please Wait.";
     var timer = new System.Diagnostics.Stopwatch();
     timer.Start();
     var tokenSource = new System.Threading.CancellationTokenSource();
     var tasks = new System.Threading.Tasks.Task<string>[10] {
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
     };
     var results = await System.Threading.Tasks.Task.WhenAny<string>(tasks);
     tokenSource.Cancel();
     timer.Stop();
     ResultTextBlock.Text = "Scenario: Similar Tasks Scenario With WhenAny.\n" + timer.Elapsed.TotalMilliseconds + " Milli Seconds the First Task to Complete.";
 }
示例#36
0
        Run()
        {
            Log.Detail("Running build");

            // TODO: should the rank collections be sorted, so that modules with fewest dependencies are first?

            var graph = Graph.Instance;
            var metaDataType = graph.BuildModeMetaData.GetType();
            var useEvaluation = CheckIfModulesNeedRebuilding(metaDataType);
            var explainRebuild = CommandLineProcessor.Evaluate(new Options.ExplainBuildReason());
            var immediateOutput = CommandLineProcessor.Evaluate(new Options.ImmediateOutput());

            ExecutePreBuild(metaDataType);

            if (!System.IO.Directory.Exists(graph.BuildRoot))
            {
                System.IO.Directory.CreateDirectory(graph.BuildRoot);
            }

            var threadCount = CommandLineProcessor.Evaluate(new Options.MultiThreaded());
            if (0 == threadCount)
            {
                threadCount = System.Environment.ProcessorCount;
            }

            System.Exception abortException = null;
            if (threadCount > 1)
            {
                var cancellationSource = new System.Threading.CancellationTokenSource();
                var cancellationToken = cancellationSource.Token;

                // LongRunning is absolutely necessary in order to achieve paralleism
                var creationOpts = System.Threading.Tasks.TaskCreationOptions.LongRunning;
                var continuationOpts = System.Threading.Tasks.TaskContinuationOptions.LongRunning;

                var scheduler = new LimitedConcurrencyLevelTaskScheduler(threadCount);

                var factory = new System.Threading.Tasks.TaskFactory(
                        cancellationToken,
                        creationOpts,
                        continuationOpts,
                        scheduler);

                var tasks = new Array<System.Threading.Tasks.Task>();
                foreach (var rank in graph.Reverse())
                {
                    foreach (var module in rank)
                    {
                        var context = new ExecutionContext(useEvaluation, explainRebuild, immediateOutput);
                        var task = factory.StartNew(() =>
                            {
                                if (cancellationToken.IsCancellationRequested)
                                {
                                    return;
                                }
                                var depTasks = new Array<System.Threading.Tasks.Task>();
                                foreach (var dep in module.Dependents)
                                {
                                    if (null == dep.ExecutionTask)
                                    {
                                        continue;
                                    }
                                    depTasks.Add(dep.ExecutionTask);
                                }
                                foreach (var dep in module.Requirements)
                                {
                                    if (null == dep.ExecutionTask)
                                    {
                                        continue;
                                    }
                                    depTasks.Add(dep.ExecutionTask);
                                }
                                System.Threading.Tasks.Task.WaitAll(depTasks.ToArray());
                                if (cancellationToken.IsCancellationRequested)
                                {
                                    return;
                                }

                                try
                                {
                                    (module as IModuleExecution).Execute(context);
                                }
                                catch (Exception ex)
                                {
                                    abortException = ex;
                                    cancellationSource.Cancel();
                                }
                                finally
                                {
                                    if (context.OutputStringBuilder != null && context.OutputStringBuilder.Length > 0)
                                    {
                                        Log.Info(context.OutputStringBuilder.ToString());
                                    }
                                    if (context.ErrorStringBuilder != null && context.ErrorStringBuilder.Length > 0)
                                    {
                                        Log.Info(context.ErrorStringBuilder.ToString());
                                    }
                                }
                            });
                        tasks.Add(task);
                        module.ExecutionTask = task;
                    }
                }
                try
                {
                    System.Threading.Tasks.Task.WaitAll(tasks.ToArray());
                }
                catch (System.AggregateException exception)
                {
                    if (!(exception.InnerException is System.Threading.Tasks.TaskCanceledException))
                    {
                        throw new Exception(exception, "Error during threaded build");
                    }
                }
            }
            else
            {
                foreach (var rank in graph.Reverse())
                {
                    if (null != abortException)
                    {
                        break;
                    }
                    foreach (IModuleExecution module in rank)
                    {
                        var context = new ExecutionContext(useEvaluation, explainRebuild, immediateOutput);
                        try
                        {
                            module.Execute(context);
                        }
                        catch (Exception ex)
                        {
                            abortException = ex;
                            break;
                        }
                        finally
                        {
                            if (context.OutputStringBuilder != null && context.OutputStringBuilder.Length > 0)
                            {
                                Log.Info(context.OutputStringBuilder.ToString());
                            }
                            if (context.ErrorStringBuilder != null && context.ErrorStringBuilder.Length > 0)
                            {
                                Log.Info(context.ErrorStringBuilder.ToString());
                            }
                        }
                    }
                }
            }

            if (null != abortException)
            {
                throw new Exception(abortException, "Error during {0}threaded build", (threadCount > 1) ? string.Empty : "non-");
            }

            ExecutePostBuild(metaDataType);
        }
示例#37
0
        public static void DownLoadFacePhoto(string resourceName, Action ErrorCallBack = null, Action SuccessCallBack = null)
        {
#if !CUSTOMSERVER
            //针对资源存放在固定的FTP服务器上的资源
            System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource();

            WebClient webClient = new WebClient();
            webClient.DownloadDataCompleted += (s, e) =>
            {
                source.Cancel();
                //区分下载出错的异常信息和下载完毕通过content-type
                if (!((WebClient)s).ResponseHeaders.GetValue("Content-Type").ToLower().Contains("application/json"))
                {
                    if (e.Error == null && e.Cancelled == false && e.Result.Length > 0)
                    {
                        lock (face_lock)
                        {
                            var data = e.Result;
                            //var str = Encoding.UTF8.GetString(e.Result);
                            var filename = Path.Combine(SDKClient.Instance.property.CurrentAccount.facePath, resourceName);
                            if (File.Exists(filename))
                            {
                                SuccessCallBack?.Invoke();
                            }
                            else if (File.Exists(filename))
                            {
                                SuccessCallBack?.Invoke();
                            }
                            else
                            {
                                File.WriteAllBytes(Path.Combine(SDKClient.Instance.property.CurrentAccount.facePath, resourceName), data);
                                SuccessCallBack?.Invoke();
                            }
                        }
                    }
                }
                else
                {
                    ErrorCallBack?.Invoke();
                    if (e.Error == null)
                    {
                        logger.Error($"下载头像失败;message:{Encoding.UTF8.GetString(e.Result)},name:{resourceName}");
                    }
                    else
                    {
                        logger.Error($"下载头像失败;message:{e.Error.Message},name:{resourceName}");
                    }
                }
            };
            Task.Run(() =>
            {
                string uri = $"{Protocol.ProtocolBase.downLoadResource}{resourceName}";
                webClient.DownloadDataAsync(new Uri(uri));
            }).ContinueWith(task =>
            {
                Task.Delay(32 * 1000, source.Token).ContinueWith(t =>
                {
                    if (t.IsCanceled)
                    {
                        return;
                    }
                    else
                    {
                        ErrorCallBack?.Invoke();
                        logger.Error($"下载头像超时;{resourceName}");
                    }
                });
            });
#else
            //针对资源名是URL形式
            Task.Run(() =>
            {
                try
                {
                    string fileName = Path.GetFileName(resourceName);
                    fileName        = Path.Combine(property.CurrentAccount.imgPath, fileName);
                    var stream      = WebRequest.Create(resourceName).GetResponse().GetResponseStream();

                    using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
                    {
                        byte[] buff = new byte[4096];
                        while (true)
                        {
                            int i = stream.Read(buff, 0, 4096);
                            fs.Write(buff, 0, i);

                            if (i == 0)
                            {
                                break;
                            }
                        }
                        fs.Flush();
                    }
                }
                catch (Exception e)
                {
                    ErrorCallBack?.Invoke();

                    logger.Error($"下载资源失败;message:{e.Message},name:{resourceName}");
                }

                SuccessCallBack?.Invoke();
            });
#endif
        }
示例#38
0
 public void Close()
 {
     _CancelGetContext.Cancel();
     _HttpListener.Close();
 }
示例#39
0
        void Launcher_BuildUpdated(Client.Launcher.BuildUpdatedEventArgs e)
        {
            HashSet<Settings.IDatFile> dats = new HashSet<Settings.IDatFile>();
            List<Settings.IAccount> accounts = new List<Settings.IAccount>();

            //only accounts with a unique dat file need to be updated

            foreach (ushort uid in Settings.Accounts.GetKeys())
            {
                var a = Settings.Accounts[uid];
                if (a.HasValue && (a.Value.DatFile == null || dats.Add(a.Value.DatFile)))
                {
                    accounts.Add(a.Value);
                }
            }

            if (accounts.Count > 0)
            {
                System.Threading.CancellationTokenSource cancel = new System.Threading.CancellationTokenSource(3000);

                try
                {
                    this.BeginInvoke(new MethodInvoker(
                        delegate
                        {
                            BeforeShowDialog();
                            try
                            {
                                activeWindows++;
                                using (formUpdating f = new formUpdating(accounts, true, true))
                                {
                                    f.Shown += delegate
                                    {
                                        cancel.Cancel();
                                    };
                                    f.ShowDialog(this);
                                }
                            }
                            finally
                            {
                                activeWindows--;
                            }
                        }));
                }
                catch { }

                try
                {
                    cancel.Token.WaitHandle.WaitOne();
                }
                catch (Exception ex)
                {
                    ex = ex;
                }

                e.Update(accounts);
            }
        }
示例#40
0
        static int Main(string[] args)
        {
            if (System.Console.BufferWidth == System.Console.WindowWidth)
            {
                System.Console.SetBufferSize(System.Console.BufferWidth * 2, System.Console.BufferHeight);
            }

            // download everything local to the site
            var commandLineApplication = new Microsoft.Extensions.CommandLineUtils.CommandLineApplication();
            var siteArgument           = commandLineApplication.Argument("site", "The site to scrape");
            var folderArgument         = commandLineApplication.Argument("folder", "The folder to scrape to");
            var updateOption           = commandLineApplication.Option("-u|--update", "Whether to update or ignore existing files", Microsoft.Extensions.CommandLineUtils.CommandOptionType.NoValue);

            commandLineApplication.HelpOption("-h|--help");
            commandLineApplication.OnExecute(() =>
            {
                var site  = siteArgument.Value;
                var local = folderArgument.Value;
                update    = updateOption.HasValue();

                Task task;

                using (var client = new System.Net.Http.HttpClient(new System.Net.Http.HttpClientHandler {
                    AllowAutoRedirect = false, AutomaticDecompression = System.Net.DecompressionMethods.None
                }))
                {
                    var cancellationTokenSource = new System.Threading.CancellationTokenSource();
                    var baseUri  = new Uri(site);
                    var basePath = GetFileName(local, baseUri);

                    if (!update && System.IO.File.Exists(basePath))
                    {
                        // just use the current
                        var links = GetLinks(System.IO.File.ReadAllText(basePath), baseUri);
                        task      = ProcessUris(client, local, update ? links : links.OrderBy(_ => System.IO.File.Exists(GetFileName(local, _)), new ExistsComparer()), cancellationTokenSource.Token);
                    }
                    else
                    {
                        task = Process(client, local, baseUri, cancellationTokenSource.Token);
                    }

                    while (!(task.IsFaulted || task.IsCompleted || task.IsCanceled))
                    {
                        System.Threading.Thread.Sleep(100);

                        if (Console.KeyAvailable)
                        {
                            var key = Console.ReadKey();
                            switch (key.Key)
                            {
                            case ConsoleKey.Escape:
                                cancellationTokenSource.Cancel();
                                break;

                            case ConsoleKey.UpArrow:
                                Delay++;
                                break;

                            case ConsoleKey.DownArrow:
                                if (Delay > 0)
                                {
                                    Delay--;
                                }

                                break;
                            }
                        }
                    }

                    if (task != null && task.IsFaulted)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.WriteLine("{0}ERROR! - {1}", currentIndent, task.Exception.ToString());
                        Console.ForegroundColor = DefaultConsoleColor;
                        return(task.Exception.HResult);
                    }
                }

                return(0);
            });

            return(commandLineApplication.Execute(args));
        }