Cancel() public method

public Cancel ( ) : void
return void
Ejemplo n.º 1
1
        private static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Console.CancelKeyPress +=
                (sender, e) =>
                {
                    e.Cancel = true;
                    cts.Cancel();
                };

            // Since Console apps do not have a SyncronizationContext, we're leveraging the built-in support
            // in WPF to pump the messages via the Dispatcher.
            // See the following for additional details:
            //   http://blogs.msdn.com/b/pfxteam/archive/2012/01/21/10259307.aspx
            //   https://github.com/DotNetAnalyzers/StyleCopAnalyzers/pull/1362
            SynchronizationContext previousContext = SynchronizationContext.Current;
            try
            {
                var context = new DispatcherSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(context);

                DispatcherFrame dispatcherFrame = new DispatcherFrame();
                Task mainTask = MainAsync(args, cts.Token);
                mainTask.ContinueWith(task => dispatcherFrame.Continue = false);

                Dispatcher.PushFrame(dispatcherFrame);
                mainTask.GetAwaiter().GetResult();
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(previousContext);
            }
        }
        public void Dulicate_message_is_detected()
        {
            var builder = new CqrsEngineBuilder();
            builder.Memory(m =>
                {
                    m.AddMemorySender("in", s => s.IdGenerator(() => "same"));
                    m.AddMemoryRouter("in", c => "memory:null");
                });
            var observer = new ImmediateEventsObserver();
            builder.Advanced.RegisterObserver(observer);

            using (var token = new CancellationTokenSource())
            using (var build = builder.Build())
            {
                var sender = build.Resolve<IMessageSender>();
                sender.SendOne(new Message());
                sender.SendOne(new Message());

                observer.Event += @event =>
                    {
                        var e = @event as EnvelopeDuplicateDiscarded;

                        if (e != null)
                        {
                            token.Cancel();
                        }
                    };
                build.Start(token.Token);
                token.Token.WaitHandle.WaitOne(10000);
                Assert.IsTrue(token.IsCancellationRequested);
            }
        }
        public void Start(Func<Task> callback, TimeSpan? interval, Action<Exception> errorCallback)
        {
            tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            task = Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    try
                    {
                        if (interval.HasValue)
                        {
                            await Task.Delay(interval.Value, token).ConfigureAwait(false);
                        }
                        else
                        {
                            tokenSource.Cancel();
                        }

                        await callback().ConfigureAwait(false);
                    }
                    catch (OperationCanceledException)
                    {
                        // nop	 
                    }
                    catch (Exception ex)
                    {
                        errorCallback(ex);
                    }
                }
            }, CancellationToken.None);
        }
Ejemplo n.º 4
1
        public static IYubicoResponse Validate(IEnumerable<string> urls, string userAgent)
        {
            var tasks = new List<Task<IYubicoResponse>>();
            var cancellation = new CancellationTokenSource();

            foreach (var url in urls)
            {
                var thisUrl = url;
                var task = new Task<IYubicoResponse>(() => DoVerify(thisUrl, userAgent), cancellation.Token);
                task.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
                tasks.Add(task);
                task.Start();
            }

            while (tasks.Count != 0)
            {
                // TODO: handle exceptions from the verify task. Better to be able to propagate cause for error.
                var completed = Task.WaitAny(tasks.Cast<Task>().ToArray());
                var task = tasks[completed];
                tasks.Remove(task);
                if (task.Result != null)
                {
                    cancellation.Cancel();
                    return task.Result;
                }
            }

            return null;
        }
        public Task SearchAsync(string searchPattern, FileSearchMode mode, int count, IFileCollection files, CancellationToken cancellationToken)
        {
            if (String.IsNullOrEmpty(searchPattern))
            {
                files.Clear();
                foreach (string filePath in pinStateService.GetList())
                    files.Add(Path.GetFileNameWithoutExtension(filePath), filePath, true);

                if (lastCancellation != null)
                {
                    lastCancellation.Cancel();
                    lastCancellation = null;
                }

                return Task.FromResult(true);
            }

            if (cancellationToken.IsCancellationRequested)
                return Async.CompletedTask;

            lastCancellation = new CancellationTokenSource();
            cancellationToken.Register(() => lastCancellation.Cancel());

            Task result = innerService.SearchAsync(searchPattern, mode, count, files, lastCancellation.Token);
            return result;
        }
Ejemplo n.º 6
1
        static void testCancellation()
        {
            IEnumerable<int> million = Enumerable.Range (3, 1000000);
            var cancelSource = new CancellationTokenSource();

            var primeNumberQuery =
                from n in million.AsParallel().WithCancellation (cancelSource.Token)
                where Enumerable.Range (2, (int) Math.Sqrt (n)).All (i => n % i > 0)
                select n;

            new Thread (() => {
                Thread.Sleep (100); // Cancel query after
                cancelSource.Cancel(); // 100 milliseconds.
            }).Start();

            try
            {
                // Start query running:
                int[] primes = primeNumberQuery.ToArray();
                // We'll never get here because the other thread will cancel us.
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Query canceled");
            }
        }
Ejemplo n.º 7
1
        public void Run()
        {
            while (true)
            {
                var fetch = CommonTasks.ExecuteScript("Crawlers\\Scripts\\Bicing.js");
                var parse = fetch.ContinueWith<Tuple<Station, NameValueCollection>[]>(Parse, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
                var store = parse.ContinueWith(Store, TaskContinuationOptions.OnlyOnRanToCompletion);

                try
                {
                    Task.WaitAll(fetch, parse, store);
                }
                catch (AggregateException e)
                {
                    e.Handle(x =>
                    {
                        System.Console.WriteLine(x.Message);
                        return true;
                    });
                }
                CancellationTokenSource source = new CancellationTokenSource();

                Task.Factory.StartNew(() => StationLoop(parse.Result), source.Token);

                Thread.Sleep(TimeSpan.FromHours(12));
                source.Cancel();
            }
        }
Ejemplo n.º 8
0
        public async void ReloadServerList()
        {
            BeginLoading();

            _reloadingCts.Cancel();
            var oldsrc = _reloadingCts;

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

            oldsrc.Cancel(false);
            try
            {
                await Task.Factory.StartNew(o => ReloadInternal((CancellationToken)o), token, token).
                ContinueWith(t =>
                {
                    if (t.Status == TaskStatus.RanToCompletion)
                    {
                        RememberLastVisiblyItems();
                    }
                });
            }
            catch (Exception)
            {
                // ignored
            }

            EndLoading();
        }
Ejemplo n.º 9
0
        /// <inheritdoc/>
        protected override Task RunTestsAsync(IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
        {
            if (!messageBus.QueueMessage(new TestStarting(this, DisplayName)))
                cancellationTokenSource.Cancel();
            else
            {
                try
                {
                    lambda();

                    if (!messageBus.QueueMessage(new TestPassed(this, DisplayName, 0, null)))
                        cancellationTokenSource.Cancel();
                }
                catch (Exception ex)
                {
                    if (!messageBus.QueueMessage(new TestFailed(this, DisplayName, 0, null, ex)))
                        cancellationTokenSource.Cancel();
                }
            }

            if (!messageBus.QueueMessage(new TestFinished(this, DisplayName, 0, null)))
                cancellationTokenSource.Cancel();

            return Task.FromResult(0);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="connection">the connection to monitor for messages</param>
        /// <param name="cts">cancellation token to cancel on error or no data received</param>
        /// <param name="timeout">timeout to wait for messages</param>
        public NMSConnectionMonitor(IConnection connection, CancellationTokenSource cts, TimeSpan? timeout = null)
        {
            QuitOk = true;
            connection.ExceptionListener += (e) =>
            {
                Trace.TraceError("Connection error: {0}", e);
                QuitOk = false;
                cts.Cancel();
            };

            if (timeout.HasValue)
            {
                _timer = new Timer((state) =>
                {
                    if (!connection.IsStarted ||
                        !_lastMsgRecd.HasValue ||
                        _lastMsgRecd.Value <= (DateTime.UtcNow.Subtract(timeout.Value)))
                    {
                        Trace.TraceInformation("Connection Monitor: Connection Stopped or No data recd for {0}, closing connection", timeout);
                        QuitOk = false;
                        cts.Cancel();
                    }
                }, null, timeout.Value, timeout.Value);
            }
        }
Ejemplo n.º 11
0
        public static async Task<List<Light>> RetrieveLights()
        {
            var cts = new CancellationTokenSource();
            List<Light> retVal = new List<Light>();
            cts.CancelAfter(5000);

            try
            {
                HttpClient client = new HttpClient();
                string ip, username;
                int port;
                SettingsService.RetrieveSettings(out ip, out port, out username);
                var response = await client.GetAsync(new Uri(string.Format("http://{0}:{1}/api/{2}/lights/", ip, port, username))).AsTask(cts.Token);

                if (!response.IsSuccessStatusCode)
                {
                    cts.Cancel();    
                }

                string jsonResponse = await response.Content.ReadAsStringAsync();

                //System.Diagnostics.Debug.WriteLine(jsonResponse);

                retVal = ParseLights(jsonResponse);
                var IgnoredTask = UpdateLightsPhraseList(retVal);
                IgnoredTask.Start();
            }
            catch (Exception)
            {
                cts.Cancel();
            }
            return retVal;
        }
Ejemplo n.º 12
0
 private static void Processor_ProcessExit(object sender, EventArgs e)
 {
     if (!_cs.IsCancellationRequested)
     {
         _cs.Cancel();
     }
 }
        public void Test()
        {
            using (var source = new CancellationTokenSource())
            {
                var dev = AzureStorage.CreateConfigurationForDev();
                WipeAzureAccount.Fast(s => s.StartsWith("test-"), dev);
                var b = new RawEngineBuilder();
                b.Dispatch(dev.CreateInbox("test-publish"), bytes =>
                    {
                        if (bytes[0] == 42)
                            source.Cancel();
                    });

                using (var engine = b.Build())
                {
                    var task = engine.Start(source.Token);

                    dev.CreateQueueWriter("test-publish").PutMessage(new byte[] {42});
                    if (!task.Wait(5000))
                    {
                        source.Cancel();
                    }
                }
            }
        }
        public static void Queue(
            this IMessageBus messageBus,
            ITest test,
            Func<ITest, IMessageSinkMessage> createTestResultMessage,
            CancellationTokenSource cancellationTokenSource)
        {
            Guard.AgainstNullArgument("messageBus", messageBus);
            Guard.AgainstNullArgument("createTestResultMessage", createTestResultMessage);
            Guard.AgainstNullArgument("cancellationTokenSource", cancellationTokenSource);

            if (!messageBus.QueueMessage(new TestStarting(test)))
            {
                cancellationTokenSource.Cancel();
            }
            else
            {
                if (!messageBus.QueueMessage(createTestResultMessage(test)))
                {
                    cancellationTokenSource.Cancel();
                }
            }

            if (!messageBus.QueueMessage(new TestFinished(test, 0, null)))
            {
                cancellationTokenSource.Cancel();
            }
        }
Ejemplo n.º 15
0
        /// <summary>モジュール名を指定してモジュールをロードします。</summary>
        /// <param name="serviceName">モジュール名</param>
        /// <param name="args">モジュールロード時のオプション(使っていません)</param>
        /// <returns>ロードされたモジュール</returns>
        public async Task<QiServiceModule> LoadService(string serviceName, params object[] args)
        {
            if (IsDisposed) throw new ObjectDisposedException(nameof(QiSession));

            int id = PublishPostId();
            QiServiceModule result = null;
            JToken errorData = new JObject();

            bool success = false;
            bool disconnected = false;

            CancellationTokenSource cts = new CancellationTokenSource();
            var token = cts.Token;

            //コードの通りだが、成功と失敗のイベントを監視しつつ通信を試す
            using (var _ = Observable.FromEventPattern<QiSessionReplyEventArgs>(this, nameof(ReplyReceived))
                .FirstAsync(ep => ep.EventArgs.Id == id)
                .Subscribe(ep =>
                {
                    success = true;
                    result = QiServiceModule.CreateFromMetaObject(this, ep.EventArgs.Data);
                    cts.Cancel();
                }))
            using (var __ = Observable.FromEventPattern<QiSessionReplyEventArgs>(this, nameof(ErrorReceived))
                .FirstAsync(ep => ep.EventArgs.Id == id)
                .Subscribe(ep =>
                {
                    success = false;
                    errorData = ep.EventArgs.Data;
                    cts.Cancel();
                }))
            using (var ___ = Observable.FromEventPattern<EventArgs>(this, nameof(Disconnected))
                .Take(1)
                .Subscribe(____ =>
                {
                    success = false;
                    disconnected = true;
                    cts.Cancel();
                }))
            {

                Post(id, "ServiceDirectory", "service", new JArray(new JValue(serviceName)));
                await Task.Delay(Timeout.Infinite, token);

                if (disconnected)
                {
                    throw new QiSessionDisconnectedException();
                }

                if(!success)
                {
                    throw new QiSessionLoadServiceFailedException(id, serviceName, errorData);
                }

                return result;

            }


        }
Ejemplo n.º 16
0
		public async Task Run(CancellationToken cancel_token)
		{
			try {
				cancel_token.ThrowIfCancellationRequested();
				await Handshake(cancel_token);
				var local_cancel = new CancellationTokenSource();
				cancel_token.Register(() => { local_cancel.Cancel(); Close(); });
				var send_messages = SendServerMessages(local_cancel.Token);
				var recv_messages = RecvAndProcessMessages(local_cancel.Token);
				Task.WaitAny(send_messages, recv_messages);
				local_cancel.Cancel();
				Close();
				Task.WaitAll(send_messages, recv_messages);
			}
			catch (IOException e) {
				if (!disposed) {
					logger.Error(e);
				}
			}
			catch (AggregateException e) {
				if (!disposed) {
					logger.Error(e);
				}
			}
			finally {
				Close();
			}
		}
Ejemplo n.º 17
0
 public void Dispose()
 {
     _callback = null;
     _state    = null;
     _changeSource?.Cancel();
     _changeSource?.Dispose();
 }
        static void Main(string[] args)
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;
            cancellationTokenSource.Cancel();
            var t2 = Task.Run(() =>
              {
                  while (true)
                  {
                      cancellationToken.ThrowIfCancellationRequested();
                      Console.WriteLine("In loop");
                      Thread.Sleep(1000);
                  }
              }, cancellationToken)
              .ContinueWith(prev =>
              {
                  Console.WriteLine($"t2 status is now {prev.Status}");
              });

            cancellationToken.Register(() => { Console.WriteLine("this will run when cancelled"); });

            Thread.Sleep(4000);
            cancellationTokenSource.Cancel();
            Console.ReadLine();
        }
Ejemplo n.º 19
0
 private void FaceCompare_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (_cts != null)
     {
         _cts.Cancel();
     }
 }
Ejemplo n.º 20
0
        protected async Task ExecuteWithProgressDialogAsync(Func<CancellationToken, Task> asyncFunc, CancellationToken pageExitCancellationToken)
        {
            await UiDispatchService.DispatchOnUiThread(async () =>
            {
                IDialogService dialogService;
                try
                {
                    dialogService = DialogService;
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                    return;
                }

                if (dialogService.IsProgressDialogOpen())
                {
                    return;
                }

                try
                {
                    var timeOutCancellationTokenSource = new CancellationTokenSource();
                    var invokeTask = asyncFunc.Invoke(timeOutCancellationTokenSource.Token);

                    if (pageExitCancellationToken.IsCancellationRequested)
                    {
                        timeOutCancellationTokenSource.Cancel();
                        pageExitCancellationToken.ThrowIfCancellationRequested();
                    }

                    await Task.WhenAny(Task.Delay(250, pageExitCancellationToken), invokeTask);

                    if (!invokeTask.IsCompleted)
                    {
                        dialogService.ShowProgressDialog();
                    }

                    if (pageExitCancellationToken.IsCancellationRequested)
                    {
                        timeOutCancellationTokenSource.Cancel();
                        pageExitCancellationToken.ThrowIfCancellationRequested();
                    }

                    await Task.WhenAny(Task.Delay(8000, pageExitCancellationToken), invokeTask);

                    if (invokeTask.IsFaulted)
                    {
                        throw invokeTask.Exception.InnerException;
                    }

                }
                finally
                {
                    dialogService.CloseProgressDialog();
                }
            });

        }
Ejemplo n.º 21
0
        public void StopListening()
        {
            StopIntervalTimer();

            if (_readCancellationTokenSource != null && _readCancellationTokenSource.Token.CanBeCanceled)
            {
                _readCancellationTokenSource.Cancel();
            }
        }
Ejemplo n.º 22
0
        private void CancellationTokenSource_CancelShouldWorkIfFirstTime()
        {
            var cancelCount = 0;
            var cts = new CancellationTokenSource();
            cts.Token.Register(() => { cancelCount++; cts.Cancel(); });
            cts.Cancel();

            Assert.IsTrue(cancelCount == 1);
        }
Ejemplo n.º 23
0
        private async Task<bool> Process(CancellationToken cancellationToken)
        {
            var result = await _queueOperator.NextAsync(
                new QueueName(_actorDescriptor.SourceQueueName));

            var cancellationTokenSource = new CancellationTokenSource();

            if (result.IsSuccessful)
            {
                TheTrace.TraceInformation("Receieved a message. Id: {0} Queue: {1} ", result.PollingResult.Id, _actorDescriptor.SourceQueueName);
                var actor = (IProcessorActor)_serviceLocator.GetService(_actorDescriptor.ActorType);
                try
                {

                    // this is NOT supposed to be awaited upon!!
                     _queueOperator.KeepExtendingLeaseAsync(result.PollingResult, TimeSpan.FromSeconds(30),
                        cancellationTokenSource.Token).SafeObserve();

                    // Would have been great to make this fixed memory foot-print with real iterable vs. list
                    var events = (await actor.ProcessAsync(result.PollingResult)).ToArray(); // the enumerable has to be turned into a list anyway. it does further on
                    var groups = events.GroupBy(x=>x.QueueName);

                    foreach (var gr in groups)
                    {
                        await _queueOperator.PushBatchAsync(gr);
                        TryDisposeMessages(gr);
                    }

                    cancellationTokenSource.Cancel();
                    await _queueOperator.CommitAsync(result.PollingResult);

                    TheTrace.TraceInformation("Processing succeeded. Id: {0} Queue: {1} " , result.PollingResult.Id, _actorDescriptor.SourceQueueName);

                }
                catch (Exception exception)
                {
                    TheTrace.TraceInformation("Processing failed. Id: {0} Queue: {1} ", result.PollingResult.Id, _actorDescriptor.SourceQueueName);
                    TheTrace.TraceError(exception.ToString());
                    cancellationTokenSource.Cancel();
                    _queueOperator.AbandonAsync(result.PollingResult).SafeObserve().Wait();

                }
                finally
                {                    
                   if (result.IsSuccessful)
                       TryDisposeMessage(result.PollingResult);
                    _serviceLocator.ReleaseService(actor);
                }
            }

            return result.IsSuccessful;
        }
        public void SignalToStop()
        {
            if (_jpegStream != null)
            {
                _jpegStream.NewFrame -= JpegStreamNewFrame;
                _jpegStream.SignalToStop();

                _tokenSource.Cancel();
                _signal.Set();

                _faceComparer.SignalToStop();
            }
        }
Ejemplo n.º 25
0
        private async Task<bool> Process(CancellationToken cancellationToken)
        {
            var result = await _queueOperator.NextAsync(
                new QueueName(_actorDescriptor.SourceQueueName));

            var cancellationTokenSource = new CancellationTokenSource();

            if (result.IsSuccessful)
            {
                TheTrace.TraceInformation("Receieved a message. Id: {0} Queue: {1} ", result.PollingResult.Id, _actorDescriptor.SourceQueueName);
                var actor = (IProcessorActor)_serviceLocator.GetService(_actorDescriptor.ActorType);
                try
                {

                    _queueOperator.KeepExtendingLeaseAsync(result.PollingResult, TimeSpan.FromSeconds(30),
                        cancellationTokenSource.Token).SafeObserve();

                    var events = (await actor.ProcessAsync(result.PollingResult)).ToArray();
                    cancellationTokenSource.Cancel();

                    await _queueOperator.CommitAsync(result.PollingResult);

                    var groups = events.GroupBy(x=>x.QueueName);

                    foreach (var gr in groups)
                    {
                        await _queueOperator.PushBatchAsync(gr);
                        TryDisposeMessages(gr);
                    }

                    TheTrace.TraceInformation("Processing succeeded. Id: {0} Queue: {1} " , result.PollingResult.Id, _actorDescriptor.SourceQueueName);

                }
                catch (Exception exception)
                {
                    TheTrace.TraceInformation("Processing failed. Id: {0} Queue: {1} ", result.PollingResult.Id, _actorDescriptor.SourceQueueName);
                    TheTrace.TraceError(exception.ToString());
                    cancellationTokenSource.Cancel();
                    _queueOperator.AbandonAsync(result.PollingResult).SafeObserve().Wait();

                }
                finally
                {                    
                   if (result.IsSuccessful)
                       TryDisposeMessage(result.PollingResult);
                    _serviceLocator.ReleaseService(actor);
                }
            }

            return result.IsSuccessful;
        }
Ejemplo n.º 26
0
        public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException()
        {
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
            {
                var ctx = new CancellationTokenSource();

                Task clientConnectToken = client.ConnectAsync(ctx.Token);
                ctx.Cancel();
                await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken);

                ctx.Cancel();
                await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token));
            }
        }
        public void Cancel()
        {
            var cts = new CancellationTokenSource();

            int[] called = { 0 };
            cts.Token.Register(l => { Assert.AreEqual("v", l); ++called[0]; }, "v");
            cts.Cancel();
            Assert.AreEqual(1, called[0], "#1");

            called[0] = 0;
            cts.Token.Register(() => { called[0] += 12; });
            cts.Cancel();
            Assert.AreEqual(12, called[0], "#2");
        }
Ejemplo n.º 28
0
 public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException()
 {
     using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
     {
         var ctx = new CancellationTokenSource();
         if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(812, PlatformID.AnyUnix)] - Unix implementation currently ignores timeout and cancellation token once the operation has been initiated
         {
             Task clientConnectToken = client.ConnectAsync(ctx.Token);
             ctx.Cancel();
             await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken);
         }
         ctx.Cancel();
         await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token));
     }
 }
Ejemplo n.º 29
0
        protected override async Task RunTestsOnMethodAsync(IMessageBus messageBus,
                                                            Type classUnderTest,
                                                            object[] constructorArguments,
                                                            MethodInfo methodUnderTest,
                                                            List<BeforeAfterTestAttribute> beforeAfterAttributes,
                                                            ExceptionAggregator aggregator,
                                                            CancellationTokenSource cancellationTokenSource)
        {
            var executionTime = 0M;
            var originalCulture = Thread.CurrentThread.CurrentCulture;
            var originalUICulture = Thread.CurrentThread.CurrentUICulture;

            try
            {
                var cultureInfo = CultureInfo.GetCultureInfo(culture);
                Thread.CurrentThread.CurrentCulture = cultureInfo;
                Thread.CurrentThread.CurrentUICulture = cultureInfo;

                executionTime =
                    await RunTestWithArgumentsAsync(messageBus,
                                                    classUnderTest,
                                                    constructorArguments,
                                                    methodUnderTest,
                                                    null,
                                                    DisplayName,
                                                    beforeAfterAttributes,
                                                    aggregator,
                                                    cancellationTokenSource);
            }
            catch (Exception ex)
            {
                if (!messageBus.QueueMessage(new Xunit.Sdk.TestStarting(this, DisplayName)))
                    cancellationTokenSource.Cancel();
                else
                {
                    if (!messageBus.QueueMessage(new Xunit.Sdk.TestFailed(this, DisplayName, executionTime, null, ex.Unwrap())))
                        cancellationTokenSource.Cancel();
                }

                if (!messageBus.QueueMessage(new Xunit.Sdk.TestFinished(this, DisplayName, executionTime, null)))
                    cancellationTokenSource.Cancel();
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = originalCulture;
                Thread.CurrentThread.CurrentUICulture = originalUICulture;
            }
        }
        void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance)
        {
            var cancel = new System.Threading.CancellationTokenSource();

            taskInstance.Canceled += (s, e) =>
            {
                cancel.Cancel();
                cancel.Dispose();
            };

            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            try
            {
                // Handle geofence state change reports
                GetGeofenceStateChangedReports(GeofenceMonitor.Current.LastKnownGeoposition);
            }
            catch (UnauthorizedAccessException)
            {
                WriteStatusToAppData("Location permissions are disabled. Enable access through the settings.");
            }
            finally
            {
                deferral.Complete();
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Execute a delegate and if it does not finish in the timeout period then terminate it
        /// </summary>
        /// <param name="obj">the extension object</param>
        /// <param name="timeout">the amount of time to wait before terminating the action</param>
        /// <param name="action">the delegate to execute</param>
        /// <param name="responseDelegate">(optional) delgate to receive reporting text on how the action finished</param>
        /// <returns>True if the action delegate completes and false otherwise</returns>
        /// <exception cref="AggregateException">Aggregates exceptions thrown in the action delegate(see InnerExceptions)</exception>
        public static bool ExecuteActionOrTimeout(this object obj, TimeSpan timeout, Action action, Action <string> responseDelegate = null)
        {
            DateTime end = DateTime.Now + timeout;

            TaskFactory factory      = new TaskFactory();
            var         cancelSource = new System.Threading.CancellationTokenSource(timeout);

            var task = factory.StartNew(action, cancelSource.Token);

            while (DateTime.Now < end)
            {
                if (task.IsCanceled)
                {
                    responseDelegate?.Invoke($"\n{action.Target}.{action.Method} cancelled before timeout");
                    return(false);
                }
                else if (task.IsFaulted)
                {
                    responseDelegate?.Invoke($"\n{action.Target}.{action.Method} faulted before timeout");
                    throw task.Exception;
                }
                else if (task.IsCompleted)
                {
                    responseDelegate?.Invoke($"\n{action.Target}.{action.Method} completed before timeout");
                    return(true);
                }
            }

            cancelSource.Cancel();

            responseDelegate?.Invoke($"\n{action.Target}.{action.Method} timed out");
            return(false);
        }
Ejemplo n.º 32
0
        private static void CancelTasksWithSoftExit()
        {
            var cts   = new System.Threading.CancellationTokenSource();
            var token = cts.Token;

            var t = new Task(
                () =>
            {
                int i = 0;
                while (true)
                {
                    // Soft exit -> check the token if cancellation is requested
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                    Console.WriteLine($"{i++}\t");
                }
            }, token

                );

            t.Start();



            Console.ReadKey();
            cts.Cancel();
        }
Ejemplo n.º 33
0
        public static T.CancellationToken ToTpl(this CancellationToken ct)
        {
            var cts = new T.CancellationTokenSource();

            ct.Register(() => cts.Cancel());
            return(cts.Token);
        }
Ejemplo n.º 34
0
        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_CameraPara.HasVideoDevice)
            {
                _CancellationTokenSource.Cancel();
                System.Threading.Thread.Sleep(500);
                this.VideoPlayer.Stop();

                if (_FaceMatchEngine != IntPtr.Zero)
                {
                    Face.Match.Close(_FaceMatchEngine);
                }
                //if (_FaceTraceEnginer != IntPtr.Zero)
                //    Face.Trace.Close(_FaceTraceEnginer);
                if (_FaceDetectEnginer != IntPtr.Zero)
                {
                    Face.Detect.Close(_FaceDetectEnginer);
                }

                //if (_FaceAgeEngine != IntPtr.Zero)
                //    Face.Age.Close(_FaceAgeEngine);
                //if (_FaceGenderEngine != IntPtr.Zero)
                //    Face.Gender.Close(_FaceGenderEngine);
            }
        }
Ejemplo n.º 35
0
 public void Stop()
 {
     try
     {
         CTS.Cancel();
     }
     catch { }
     try { t1.Abort(); }
     catch { }
     try { t2.Abort(); }
     catch { }
     foreach (var a in clients)
     {
         try
         {
             a.Client.Close();
         }
         catch { }
     }
     try
     {
         tcpl.Stop();
     }
     catch { }
     System.Threading.Thread.Sleep(500);
 }
Ejemplo n.º 36
0
		public static void Main (string[] args)
		{
			ButtonEvents buts = new ButtonEvents ();
			var tokenSource = new CancellationTokenSource();
      		var token = tokenSource.Token;

			var dialog = new InfoDialog("Attach distance sensor", false);
			dialog.Show();
			var sensor = SensorAttachment.Wait<MSAngleSensor>(token);//wait for sensor to attached on any port
			LcdConsole.WriteLine("Up reset angle");
			LcdConsole.WriteLine("Down read RMP");
			LcdConsole.WriteLine("Enter read angle");
			LcdConsole.WriteLine("Left read raw");
			LcdConsole.WriteLine("Esc. terminate");

			buts.EscapePressed += () => { 
				tokenSource.Cancel();
			};
			buts.EnterPressed += () => {
				LcdConsole.WriteLine ("Angle: " + sensor.ReadAngle().ToString());
			};
			buts.UpPressed += () => { 
				LcdConsole.WriteLine ("Reset angle");
				sensor.ResetAngle();
			};
			buts.DownPressed += () => { 
				LcdConsole.WriteLine ("Read RPM: " +  sensor.ReadRPM().ToString());
			};
			buts.LeftPressed += () => { 
				LcdConsole.WriteLine ("Read raw: " +  sensor.ReadRAW().ToString());
			};
			token.WaitHandle.WaitOne();
		}
Ejemplo n.º 37
0
        static void Main(string[] args)
        {
            map.Add(0, 0);
            map.Add(1, 1);

            System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();
            //signalDetect(outputFolder + "signal.csv", cts);
            //BitSignalDetect(outputFolder + "signal.csv", cts);
            //MorseSignalDetect("morse.csv", cts);
            //simpleTest(cts);
            WeatherDataOutput("WeatherData.csv", cts);
            //dumpSignalIQ(outputFolder + "IQ.csv", cts);
            //dumpSignalIQRAW(outputFolder + "IQRaw.bin", cts);
            //downSameTest("SingalIQ.csv", "SingalIQ_Down1000.csv",cts);
            //dumpIQToWaveFile(outputFolder+"IQ.csv", outputFolder+"Wave.csv", cts);
            //dumpIQToLPFWaveFile(outputFolder + "IQ.csv", outputFolder + "LPF.csv", cts);
            //dumpIQToLPFWaveSQFile(outputFolder + "IQ.csv", outputFolder + "LPFSQ.csv", 0.6f,cts);
            //dumpIQToLPF_Wave_MA_SQFile(outputFolder + "IQ.csv", outputFolder + "LPF_MV_SQ.csv", 0.3f, cts);
            //dumpIQToLPF_Wave_MA_SQ_SCFile(outputFolder + "IQ.csv", outputFolder + "LPF_MV_SQ_SC.csv", 0.3f, cts);
            dumpQueue(cts.Token);
            Console.ReadLine();
            cts.Cancel();
            Console.WriteLine("waiting for threads exit...");
            PipelineManager.Default.WaitAllExit();
            Console.WriteLine("done");
        }
        public override long RunPass()
        {
            _queueEventProcessor.Reset();

            var cts = new CancellationTokenSource();
            Task.Factory.StartNew(_queueEventProcessor.Run, cts.Token);

            var sw = Stopwatch.StartNew();

            for (var i = 0; i < Iterations; i++)
            {
                _queue.Add(i);
            }

            while (!_queueEventProcessor.Done)
            {
                // busy spin
            }

            var opsPerSecond = (Iterations * 1000L) / (sw.ElapsedMilliseconds);

            cts.Cancel(true);

            Assert.AreEqual(ExpectedResult, _queueEventProcessor.Value, "RunQueuePass");

            return opsPerSecond;
        }
        public FetchedJobsWatcherFacts()
        {
            var options = new RedisStorageOptions() { Db = RedisUtils.GetDb() };
            _storage = new RedisStorage(RedisUtils.GetHostAndPort(), options);
			_cts = new CancellationTokenSource();
			_cts.Cancel();
        }
Ejemplo n.º 40
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var cache = GetDataFolder();
            using (var source = new CancellationTokenSource())
            {
                var builder = Sys.Configure(cache);
                var fastSubject = new Subject<ISystemEvent>();
                builder.Advanced.Observers.Clear();
                builder.Advanced.RegisterObserver(fastSubject);
                using (var host = builder.Build())
                {
                    Console.WriteLine("Starting host");
                    var task = host.Start(source.Token);
                    var form = new Form1(host, fastSubject);
                    form.FormClosing += (sender, args) => source.Cancel();

                    Application.Run(form);

                    task.Wait(5000);
                }
            }
        }
Ejemplo n.º 41
0
        public void TestWaitReleaseAsyncWithCancellation()
        {
            // TODO: rewrite test once cancellation is properly supported during systematic testing.
            this.Test(async() =>
            {
                Semaphore semaphore = Semaphore.Create(1, 1);
                Specification.Assert(semaphore.CurrentCount is 1, "Semaphore count is {0} instead of 1.",
                                     semaphore.CurrentCount);

                SystemTasks.CancellationTokenSource tokenSource = new SystemTasks.CancellationTokenSource();
                Task task = Task.Run(async() =>
                {
                    await Task.Delay(1);
                    tokenSource.Cancel();
                });

                await semaphore.WaitAsync(tokenSource.Token);
                Specification.Assert(semaphore.CurrentCount is 0 || semaphore.CurrentCount is 1,
                                     "Semaphore count is {0} instead of 0 or 1.", semaphore.CurrentCount);
                semaphore.Release();
                Specification.Assert(semaphore.CurrentCount is 1, "Semaphore count is {0} instead of 1.",
                                     semaphore.CurrentCount);

                await task;
                semaphore.Dispose();
            });
        }
        private static async Task CancelAllWhenAnyCompletes(Task leaderTask, Task renewLeaseTask, CancellationTokenSource cts)
        {
            await Task.WhenAny(leaderTask, renewLeaseTask);

            // Cancel the user's leader task or the renewLease Task, as it is no longer the leader.
            cts.Cancel();

            var allTasks = Task.WhenAll(leaderTask, renewLeaseTask);
            try
            {
                await Task.WhenAll(allTasks);
            }
            catch (Exception)
            {
                if (allTasks.Exception != null)
                {
                    allTasks.Exception.Handle(ex =>
                    {
                        if (!(ex is OperationCanceledException))
                        {
                            Trace.TraceError(ex.Message);
                        }

                        return true;
                    });
                }
            }
        }
Ejemplo n.º 43
0
        public static void RunTaskFactoryTests_Cancellation_Negative()
        {
            CancellationTokenSource cancellationSrc = new CancellationTokenSource();

            //Test constructor that accepts cancellationToken
            cancellationSrc.Cancel();
            TaskFactory tf = new TaskFactory(cancellationSrc.Token);
            var cancelledTask = tf.StartNew(() => { });
            EnsureTaskCanceledExceptionThrown(() => cancelledTask.Wait());

            // Exercising TF<int>(cancellationToken) with a cancelled token
            cancellationSrc.Cancel();
            TaskFactory<int> tfi = new TaskFactory<int>(cancellationSrc.Token);
            cancelledTask = tfi.StartNew(() => 0);
            EnsureTaskCanceledExceptionThrown(() => cancelledTask.Wait());
        }
Ejemplo n.º 44
0
Archivo: Startup.cs Proyecto: krwq/cli
        public static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("KestrelHelloWorld <url to host>");
                return 1;
            }

            var url = new Uri(args[0]);
            Args = string.Join(" ", args);

            var host = new WebHostBuilder()
                .UseServer("Microsoft.AspNetCore.Server.Kestrel")
                .UseUrls(url.ToString())
                .UseStartup<Startup>()
                .Build();

            ServerCancellationTokenSource = new CancellationTokenSource();

            // shutdown server after 20s.
            var shutdownTask = Task.Run(async () =>
            {
                await Task.Delay(20000);
                ServerCancellationTokenSource.Cancel();
            });

            host.Run(ServerCancellationTokenSource.Token);
            shutdownTask.Wait();

            return 0;
        }
Ejemplo n.º 45
0
 public void Disconnect()
 {
     if (!IsConnected)
     {
         return;
     }
     CancelListen.Cancel();
 }
Ejemplo n.º 46
0
        public void Stop()
        {
            if (Log.IsTraceEnabled)
            {
                _log.Trace(string.Format(Resources.ProcessorThreadStopping, _thread.ManagedThreadId,
                                         _processor.GetType().FullName));
            }

            _cancellationTokenSource.Cancel();

            _processor.AttemptDispose();

            if (_thread.IsAlive)
            {
                _thread.Join(ThreadJoinTimeoutInterval);
            }
        }
Ejemplo n.º 47
0
 private void ExitMenuButton_Click(object sender, EventArgs e)
 {
     if (Table.Rows.Count > 0)
     {
         cts?.Cancel();
         Add.Wait();
         Add.Dispose();
     }
     Application.Exit();
 }
Ejemplo n.º 48
0
        public void StreamThreadCommitIntervalWorkflow()
        {
            var source = new System.Threading.CancellationTokenSource();
            var config = new StreamConfig <StringSerDes, StringSerDes>();

            config.ApplicationId    = "test";
            config.Guarantee        = ProcessingGuarantee.AT_LEAST_ONCE;
            config.PollMs           = 1;
            config.CommitIntervalMs = 1;

            var serdes  = new StringSerDes();
            var builder = new StreamBuilder();

            builder.Stream <string, string>("topic").To("topic2");

            var topo = builder.Build();

            var supplier = new SyncKafkaSupplier();
            var producer = supplier.GetProducer(config.ToProducerConfig());
            var consumer = supplier.GetConsumer(config.ToConsumerConfig("test-consum"), null);

            consumer.Subscribe("topic2");
            var thread = StreamThread.Create(
                "thread-0", "c0",
                topo.Builder, new StreamMetricsRegistry(), config,
                supplier, supplier.GetAdmin(config.ToAdminConfig("admin")),
                0) as StreamThread;

            thread.Start(source.Token);
            producer.Produce("topic", new Confluent.Kafka.Message <byte[], byte[]>
            {
                Key   = serdes.Serialize("key1", new SerializationContext()),
                Value = serdes.Serialize("coucou", new SerializationContext())
            });
            //WAIT STREAMTHREAD PROCESS MESSAGE
            System.Threading.Thread.Sleep(100);
            var message = consumer.Consume(100);

            Assert.AreEqual("key1", serdes.Deserialize(message.Message.Key, new SerializationContext()));
            Assert.AreEqual("coucou", serdes.Deserialize(message.Message.Value, new SerializationContext()));

            var offsets = thread.GetCommittedOffsets(new List <TopicPartition> {
                new TopicPartition("topic", 0)
            },
                                                     TimeSpan.FromSeconds(10)).ToList();

            Assert.AreEqual(1, offsets.Count);
            Assert.AreEqual(1, offsets[0].Offset.Value);
            Assert.AreEqual(0, offsets[0].TopicPartition.Partition.Value);
            Assert.AreEqual("topic", offsets[0].Topic);

            source.Cancel();
            thread.Dispose();
        }
Ejemplo n.º 49
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_CameraPara.HasVideoDevice)
            {
                _CancellationTokenSource.Cancel();
                System.Threading.Thread.Sleep(500);
                this.VideoPlayer.Stop();

                ArcFace.Api.Close();
            }
        }
Ejemplo n.º 50
0
 public bool TryDequeue(out T value, int timeout = Timeout.Infinite)
 {
     lock (queue)
     {
         while (queue.Count == 0)
         {
             if (closing || (timeout < Timeout.Infinite) || !Monitor.Wait(queue, timeout))
             {
                 value = default(T);
                 CancellationTokenSource?.Cancel();
                 value.Dispose();
                 return(false);
             }
         }
         CancellationTokenSource?.Cancel();
         value = (T)queue.Dequeue();
         value.Dispose();
         GC.Collect();
         return(true);
     }
 }
        public void StopRecording()
        {
            if (recorder != null)
            {
                recorder.Stop();
                isRecording = false;
                token.Cancel();

                recorder.Release();
                recorder = null;
            }
            CopyWaveFile(GetTempFilename(), filePath);
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Closes the device.
        /// </summary>
        /// <returns></returns>
        public async Task CloseAsync()
        {
            if (m_cts != null)
            {
                m_closeTask = new TaskCompletionSource <bool>();
                if (m_cts != null)
                {
                    m_cts.Cancel();
                }
                m_cts = null;
            }
            await m_closeTask.Task;

            await CloseStreamAsync(m_stream);

            m_stream = null;
            lock (m_lockObject)
            {
                m_isOpening = false;
                IsOpen      = false;
            }
        }
Ejemplo n.º 53
0
        static void Main(string[] args)
        {
            var options = new Options();

            if (CommandLine.Parser.Default.ParseArgumentsStrict(args, options))
            {
                var client           = new Statsd(options.Host, options.Port, prefix: options.Namespace, connectionType: options.UseTCP ? ConnectionType.Tcp : ConnectionType.Udp);
                var tokenSource      = new System.Threading.CancellationTokenSource();
                var stopwatch        = Stopwatch.StartNew();
                var totalMetricsSent = 0;
                var letters          = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
                var tasks            = new List <Task>();
                int numThreads       = options.Threads == 0 ? 1 : options.Threads;
                for (int count = 0; count < numThreads; count++)
                {
                    int myTaskNumber = count;
                    var task         = Task.Factory.StartNew(() =>
                    {
                        var rnd        = new Random();
                        int taskNumber = myTaskNumber;
                        if (taskNumber == 0)
                        {
                            Console.WriteLine("Feeding stats to {0}:{1}, ctrl+c to exit.", options.Host, options.Port);
                        }
                        while (true)
                        {
                            client.LogCount("test.count.one." + rnd.Next(5));
                            client.LogCount("test.count.bigValue", rnd.Next(50));
                            client.LogTiming("test.timing." + rnd.Next(5), rnd.Next(100, 2000));
                            client.LogGauge("test.gauge." + rnd.Next(5), rnd.Next(100));
                            client.LogCalendargram("test.calendargram.users", letters.Next(), "m");
                            Thread.Sleep(options.Delay);
                            Interlocked.Add(ref totalMetricsSent, 4);

                            if (taskNumber == 0 && stopwatch.ElapsedMilliseconds >= 5000)
                            {
                                Console.WriteLine("Total sent: {0}", totalMetricsSent);
                                stopwatch.Restart();
                            }
                        }
                    },
                                                             tokenSource.Token);
                    tasks.Add(task);
                }
                Console.CancelKeyPress += (sender, e) =>
                {
                    tokenSource.Cancel();
                };
                Task.WaitAll(tasks.ToArray());
            }
        }
Ejemplo n.º 54
0
    public void Stop()
    {
        Log.Info("Stopping...");
        shutdown = true;
        using (stopLoop)
        {
            stopLoop.Cancel();
            using (loopTask)
            {
                loopTask.Wait();
            }
        }

        Log.Info("Stopped");
    }
Ejemplo n.º 55
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_VideoSource != null)
            {
                _CancellationTokenSource.Cancel();
                for (int i = 0; i < 10; i++)
                {
                    if (_MatchTask.Status == TaskStatus.RanToCompletion)
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                }
                this.VideoPlayer.Stop();

                ArcFace.Api.Close();
            }
        }
Ejemplo n.º 56
0
 public void Stop()
 {
     try
     {
         if (Task != null && CancellationTokenSource != null)
         {
             CancellationTokenSource.Cancel();
         }
         if (Task != null)
         {
             Task.Abort();
             Task = null;
         }
     }
     catch (Exception ee)
     {
     }
 }
Ejemplo n.º 57
0
        /// <summary>
        /// Stops the timer.
        /// </summary>
        private void Stop()
        {
            if (_cancellationTokenSource != null)
            {
                _cancellationTokenSource.Cancel();
                _cancellationTokenSource = null;
            }

#if USE_INTERNAL_TIMER
            lock (_lock)
            {
                if (_timer != null)
                {
                    _timer.Change(Timeout.Infinite, Timeout.Infinite);
                    _timer = null;
                }
            }
#endif
        }
Ejemplo n.º 58
0
        private async Task ShowPanel(Label label, Control panel)
        {
            panel.BringToFront();
            panel.Visible = true;
            label.Visible = false;
            panel.Focus();

            var cancel = new System.Threading.CancellationTokenSource();
            var token  = cancel.Token;

            EventHandler visibleChanged = null;

            visibleChanged = delegate
            {
                cancel.Cancel();
            };

            panel.VisibleChanged += visibleChanged;

            var r = this.RectangleToScreen(panel.Bounds);

            do
            {
                try
                {
                    await Task.Delay(500, token);
                }
                catch (TaskCanceledException)
                {
                    break;
                }
            }while (forceShowPanel || r.Contains(Cursor.Position) || Control.MouseButtons.HasFlag(MouseButtons.Left));

            panel.VisibleChanged -= visibleChanged;

            if (!cancel.IsCancellationRequested)
            {
                panel.Visible = false;
                label.Visible = true;
            }

            cancel.Dispose();
        }
Ejemplo n.º 59
0
        private void Dispose()
        {
            Trace.WriteLine("Disposing");
            if (IsDisposed)
            {
                return;
            }

            // should cancel all registered events
            CancellationTokenSource.Cancel();

            // issue into messenger
            Messenger.IssueCancellation(CancellationTokenSource);

            // should close out database and issue cancellation to token
            Messenger.Dispose();

            IsDisposed = true;
            Trace.WriteLine("Cleanup complete");
        }
Ejemplo n.º 60
0
        private void queryBtn_Click(object sender, EventArgs e)
        {
            if (_cts != null)
            {
                _cts.Cancel();
            }
            this.ClearAll();

            var c = CriteriaOperator.Parse("CaptureTime >= ? And CaptureTime <= ?",
                                           this.TimeRange.From, this.TimeRange.To);

            videoCollection.Criteria = c;

            pageSelector             = new XPPageSelector();
            pageSelector.PageSize    = 50;
            pageSelector.CurrentPage = 0;
            pageSelector.Collection  = videoCollection;

            UpdateCurrentPage();
        }