Exemplo n.º 1
22
 static ICrossBoard GenerateFirstCrossWord(ICrossBoard board, ICrossDictionary dictionary, string puzzle)
 {
     var placer = new PuzzlePlacer(board, puzzle);
     var cts = new CancellationTokenSource();
     var mre = new ManualResetEvent(false);
     ICrossBoard successFullBoard = null;
     foreach (var boardWithPuzzle in placer.GetAllPossiblePlacements(dictionary))
     {
         //boardWithPuzzle.WriteTo(new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding) { AutoFlush = true });
         var gen = new CrossGenerator(dictionary, boardWithPuzzle);
         var t = Task.Factory.StartNew(() =>
                                   {
                                       foreach (var solution in gen.Generate())
                                       {
                                           successFullBoard = solution;
                                           cts.Cancel();
                                           mre.Set();
                                           break; //interested in the first one
                                       }
                                   }, cts.Token);
         if (cts.IsCancellationRequested)
             break;
     }
     mre.WaitOne();
     return successFullBoard;
 }
Exemplo n.º 2
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();
            }
        }
        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 async Task Start(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                Settings.Default.Reload();
                var imageInfo = GetLatestImageInfo();
                if (imageInfo != null)
                {
                    var image = AssembleImageFrom(imageInfo);
                    var imageFile = SaveImage(image);
                    Wallpaper.Set(imageFile, Wallpaper.Style.Fit);
                }

                if (Settings.Default.Interval > 0)
                {
                    _internalTokenSource = new CancellationTokenSource();
                    using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_internalTokenSource.Token, token))
                    {
                        try
                        {
                            await Task.Delay(TimeSpan.FromMinutes(Settings.Default.Interval), linkedCts.Token);
                        }
                        catch
                        {
                            // ignore exception raised by token cancellation
                        }
                    }
                }
            }
        }
Exemplo n.º 5
1
 public CancelableTask(Action task, Action onSuccess)
 {
     _cancellationTokenSource = new CancellationTokenSource();
     _cancellationToken = _cancellationTokenSource.Token;
     _task = task;
     _onSuccess = onSuccess;
 }
Exemplo n.º 6
1
        public async Task ExecuteAsync_calls_Commit_if_no_transaction()
        {
            var mockModificationCommandBatch = new Mock<ModificationCommandBatch>();
            mockModificationCommandBatch.Setup(m => m.ModificationCommands.Count).Returns(1);

            var mockRelationalConnection = new Mock<IRelationalConnection>();
            var transactionMock = new Mock<IDbContextTransaction>();

            IDbContextTransaction currentTransaction = null;
            mockRelationalConnection.Setup(m => m.BeginTransaction()).Returns(() => currentTransaction = transactionMock.Object);
            mockRelationalConnection.Setup(m => m.CurrentTransaction).Returns(() => currentTransaction);

            var cancellationToken = new CancellationTokenSource().Token;

            var batchExecutor = new BatchExecutor();

            await batchExecutor.ExecuteAsync(new[] { mockModificationCommandBatch.Object }, mockRelationalConnection.Object, cancellationToken);

            mockRelationalConnection.Verify(rc => rc.OpenAsync(cancellationToken));
            mockRelationalConnection.Verify(rc => rc.Close());
            transactionMock.Verify(t => t.Commit());

            mockModificationCommandBatch.Verify(mcb => mcb.ExecuteAsync(
                It.IsAny<IRelationalConnection>(),
                cancellationToken));
        }
Exemplo n.º 7
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");
            }
        }
Exemplo n.º 8
1
        public static List<ClrType> GetDelegateTypes(ClrDump clrDump)
        {
            CancellationTokenSource token = new CancellationTokenSource();
            clrDump.MessageBus.BeginTask("Analyzing delegate types...", token);
            List<ClrType> delegates = new List<ClrType>();
            var delegateType = clrDump.GetClrType(typeof(MulticastDelegate).FullName);

            foreach(var type in  clrDump.AllTypes)
            {
                clrDump.MessageBus.Status($"Analyzing delegate type: {type.Name}");
                if (token.IsCancellationRequested)
                {
                    break;
                }

                if ( type.BaseType != null && type.BaseType == delegateType )
                {
                    clrDump.MessageBus.Status($"Analyzing delegate type: counting instances for {type.Name}");
                    int nb = clrDump.CountInstances(type);
                    if (nb > 0)
                    {
                        delegates.Add(type);
                    }
                }
            }

            clrDump.MessageBus.EndTask("Delegate types analyzed.");
            return delegates.GroupBy(t => t.Name).Select(g => g.First()).ToList();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AsynchronousTraceListenerWrapper" /> class.
        /// </summary>
        /// <param name="wrappedTraceListener">The wrapped trace listener.</param>
        /// <param name="ownsWrappedTraceListener">Indicates whether the wrapper should dispose the wrapped trace listener.</param>
        /// <param name="bufferSize">Size of the buffer for asynchronous requests.</param>
        /// <param name="maxDegreeOfParallelism">The max degree of parallelism for thread safe listeners. Specify <see langword="null"/> to use the current core count.</param>
        /// <param name="disposeTimeout">The timeout for waiting to complete buffered requests when disposing. When <see langword="null" /> the default of <see cref="Timeout.InfiniteTimeSpan" /> is used.</param>
        public AsynchronousTraceListenerWrapper(
            TraceListener wrappedTraceListener,
            bool ownsWrappedTraceListener = true,
            int? bufferSize = DefaultBufferSize,
            int? maxDegreeOfParallelism = null,
            TimeSpan? disposeTimeout = null)
        {
            Guard.ArgumentNotNull(wrappedTraceListener, "wrappedTraceListener");
            CheckBufferSize(bufferSize);
            CheckMaxDegreeOfParallelism(maxDegreeOfParallelism);
            CheckDisposeTimeout(disposeTimeout);

            this.wrappedTraceListener = wrappedTraceListener;
            this.ownsWrappedTraceListener = ownsWrappedTraceListener;
            this.disposeTimeout = disposeTimeout ?? Timeout.InfiniteTimeSpan;

            this.closeSource = new CancellationTokenSource();
            this.requests = bufferSize != null ? new BlockingCollection<Action<TraceListener>>(bufferSize.Value) : new BlockingCollection<Action<TraceListener>>();

            if (this.wrappedTraceListener.IsThreadSafe)
            {
                this.maxDegreeOfParallelism = maxDegreeOfParallelism.HasValue ? maxDegreeOfParallelism.Value : Environment.ProcessorCount;
                this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequestsInParallel, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
            else
            {
                this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequests, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
        }
Exemplo n.º 10
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;
        }
Exemplo n.º 12
1
        private async Task run(params string[] args)
        {
            _logger.LogInformation("Ready to serve");

            var msg = Configuration["msg"];
            var env = Configuration["ASPNET_ENV"];

            if (env == "Development")
            {
                Console.WriteLine("You played the shareware, now buy the game");
            }
            else
            {
                Console.WriteLine("Ready to serve, my lord.");
            }

            if (string.IsNullOrEmpty(msg))
            {
                Console.WriteLine("Even elder races get tired of waiting.");
            }
            else
            {
                Console.WriteLine($"By your command: {msg}");
            }

            using (var currentRunCancellationSource = new CancellationTokenSource())
            {
                var dnxTask = WaitForDnxToExitAsync(currentRunCancellationSource.Token);

                int finishedTaskIndex = Task.WaitAny(dnxTask);
            }

            _logger.LogInformation("Job's done");
        }
Exemplo n.º 13
1
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            var ts = new CancellationTokenSource();
            var host = Bootstrapper.Boot();
            host.Start(ts.Token);
            //            var bus = new FakeBus();
            //
            //            var storage = new EventStore(bus);
            //            var rep = new Repository<InventoryItem>(storage);
            //            var commands = new InventoryCommandHandlers(rep);
            //            bus.RegisterHandler<CheckInItemsToInventory>(commands.Handle);
            //            bus.RegisterHandler<CreateInventoryItem>(commands.Handle);
            //            bus.RegisterHandler<DeactivateInventoryItem>(commands.Handle);
            //            bus.RegisterHandler<RemoveItemsFromInventory>(commands.Handle);
            //            bus.RegisterHandler<RenameInventoryItem>(commands.Handle);
            //            var detail = new InvenotryItemDetailView();
            //            bus.RegisterHandler<InventoryItemCreated>(detail.Handle);
            //            bus.RegisterHandler<InventoryItemDeactivated>(detail.Handle);
            //            bus.RegisterHandler<InventoryItemRenamed>(detail.Handle);
            //            bus.RegisterHandler<ItemsCheckedInToInventory>(detail.Handle);
            //            bus.RegisterHandler<ItemsRemovedFromInventory>(detail.Handle);
            //            var list = new InventoryListView();
            //            bus.RegisterHandler<InventoryItemCreated>(list.Handle);
            //            bus.RegisterHandler<InventoryItemRenamed>(list.Handle);
            //            bus.RegisterHandler<InventoryItemDeactivated>(list.Handle);
            //            ServiceLocator.Bus = bus;
        }
Exemplo n.º 14
1
            public void WhenProcessTimesOut_TaskIsCanceled()
            {
                // Arrange
                const int expectedExitCode = 123;
                const int millisecondsForTimeout = 3 * 1000;
                const int millisecondsToSleep = 5 * 1000;
                const int expectedStandardOutputLineCount = 5;
                const int expectedStandardErrorLineCount = 3;

                // Act
                var pathToConsoleApp = typeof(DummyConsoleApp.Program).Assembly.Location;
                var arguments = String.Join(" ", expectedExitCode, millisecondsToSleep, expectedStandardOutputLineCount, expectedStandardErrorLineCount);
                var startInfo = new ProcessStartInfo(pathToConsoleApp, arguments);
                var cancellationToken = new CancellationTokenSource(millisecondsForTimeout).Token;
                var task = ProcessEx.RunAsync(startInfo, cancellationToken);

                // Assert
                Assert.IsNotNull(task);
                try
                {
                    var results = task.Result;
                    Assert.Fail("Timeout did not occur");
                }
                catch (AggregateException aggregateException)
                {
                    // expected
                    Assert.AreEqual(1, aggregateException.InnerExceptions.Count);
                    var innerException = aggregateException.InnerExceptions.Single();
                    Assert.IsInstanceOfType(innerException, typeof(OperationCanceledException));
                    var canceledException = innerException as OperationCanceledException;
                    Assert.IsNotNull(canceledException);
                    Assert.IsTrue(cancellationToken.IsCancellationRequested);
                }
                Assert.AreEqual(TaskStatus.Canceled, task.Status);
            }
Exemplo n.º 15
1
        public CommandProcessor(ICommandProcessingStrategy processingStrategy,
                                ICommandQueue commandQueue)
        {
            _processingStrategy = processingStrategy;
            _commandQueue = commandQueue;

            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;
            var task = new Task(
                () =>
                    {
                        while (!token.IsCancellationRequested)
                        {
                            var cmd = _commandQueue.Dequeue();
                            while (cmd != null)
                            {
                                _processingStrategy.ProcessCommand(cmd.Execute);
                                cmd = commandQueue.Dequeue();
                            }
                            Thread.Sleep(100);
                        }
                    },
                token,
                TaskCreationOptions.LongRunning);
            task.Start();
        }
Exemplo n.º 16
1
        private void search_button_click(object sender, RoutedEventArgs e)
        {
            clear_interface();

            //
            // Stop the previous search.
            //

            if (_searchCts != null && _searchCts.IsCancellationRequested == false)
            {
                _searchCts.Cancel();
            }

            //
            // Start a new search.
            //

            if ((_currentSearchTerm = _textBox.Text).IsNullOrEmpty())
            {
                return;
            }

            _searchCts = new CancellationTokenSource();
            start_search();
        }
Exemplo n.º 17
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 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);
        }
Exemplo n.º 19
1
        public async Task<XLocation> GetQuickLocation()
        {
            Setup();

            var loc = new XLocation();

            _cancelSource = new CancellationTokenSource();

            await _geolocator.GetPositionAsync(1500, _cancelSource.Token, false)
                .ContinueWith(t =>
                {

                    if (t.IsCanceled || t.IsFaulted)
                    {
                        var x = new XLocation();
                        x.IsResolved = false;
                        x.Status = XPositionStatus.NotAvailble;
                        return x;
                    }
                        
                    loc.Latitude = t.Result.Latitude;
                    loc.Longitude = t.Result.Longitude;
                    loc.Accuracy = t.Result.Accuracy;
                    loc.Heading = t.Result.Heading;
                    loc.IsEnabled = true;
                    loc.IsResolved = true;
                    loc.Status = XPositionStatus.Ready;
                    return loc;
                }, _scheduler);
            return loc;
        }
        //probe==StartBounder
        public bool GeneratePasswords(int[] probe, int[] startBoundary, int[] endBoundary, int depth, int range, CancellationToken ct, CancellationTokenSource tokenSource, Action<string> sendPassword)
        {
            bool result = false;
            char[] probeChar = CharForThread(probe, _options);

            string probeString = String.Join("", probeChar);

            if (depth==0)
            {
                Console.WriteLine(probeString);
                if (VerifyMd5Hash(probeString))
                {
                    Password = probeString;
                    sendPassword(Password);
                    return true;
                }
                return false;
            }
            if (ct.IsCancellationRequested)
            {
                Console.WriteLine("Task is canceled");
            }

            if (probe.SequenceEqual(endBoundary)) return false;

            for (int i = 0; i < range; i++)
                {
                    probe[depth - 1] = i;
                    result = GeneratePasswords(probe, startBoundary, endBoundary, depth - 1, range, ct, tokenSource, sendPassword);
                    if (result) break;
                }
                return result;
        }
            internal AnalysisQueue(VsProjectAnalyzer analyzer) {
                _workEvent = new AutoResetEvent(false);
                _cancel = new CancellationTokenSource();
                _analyzer = analyzer;

                // save the analysis once it's ready, but give us a little time to be
                // initialized and start processing stuff...
                _lastSave = DateTime.Now - _SaveAnalysisTime + TimeSpan.FromSeconds(10);

                _queue = new List<IAnalyzable>[PriorityCount];
                for (int i = 0; i < PriorityCount; i++) {
                    _queue[i] = new List<IAnalyzable>();
                }
                _enqueuedGroups = new HashSet<IGroupableAnalysisProject>();

                _workThread = new Thread(Worker);
                _workThread.Name = "Node.js Analysis Queue";
                _workThread.Priority = ThreadPriority.BelowNormal;
                _workThread.IsBackground = true;

                // start the thread, wait for our synchronization context to be created
                using (AutoResetEvent threadStarted = new AutoResetEvent(false)) {
                    _workThread.Start(threadStarted);
                    threadStarted.WaitOne();
                }
            }
		public DatabaseBulkOperations(DocumentDatabase database, TransactionInformation transactionInformation, CancellationTokenSource tokenSource, CancellationTimeout timeout)
		{
			this.database = database;
			this.transactionInformation = transactionInformation;
			this.tokenSource = tokenSource;
			this.timeout = timeout;
		}
Exemplo n.º 23
1
		/// <summary>
		/// Starts to run a build inside the SharpDevelop GUI.
		/// Only one build can run inside the GUI at one time.
		/// </summary>
		/// <param name="project">The project/solution to build.</param>
		/// <param name="options">The build options.</param>
		public static void BuildInGui(IBuildable project, BuildOptions options)
		{
			if (project == null)
				throw new ArgumentNullException("project");
			if (options == null)
				throw new ArgumentNullException("options");
			WorkbenchSingleton.AssertMainThread();
			if (guiBuildCancellation != null) {
				BuildResults results = new BuildResults();
				WorkbenchSingleton.StatusBar.SetMessage(Core.ResourceService.GetString("MainWindow.CompilerMessages.MSBuildAlreadyRunning"));
				BuildError error = new BuildError(null, Core.ResourceService.GetString("MainWindow.CompilerMessages.MSBuildAlreadyRunning"));
				results.Add(error);
				TaskService.Add(new Task(error));
				results.Result = BuildResultCode.MSBuildAlreadyRunning;
				if (options.Callback != null) {
					options.Callback(results);
				}
			} else {
				guiBuildCancellation = new CancellationTokenSource();
				IProgressMonitor progressMonitor = WorkbenchSingleton.StatusBar.CreateProgressMonitor(guiBuildCancellation.Token);
				guiBuildTrackedFeature = AnalyticsMonitorService.TrackFeature("ICSharpCode.SharpDevelop.Project.BuildEngine.Build");
				WorkbenchSingleton.StatusBar.SetMessage(StringParser.Parse("${res:MainWindow.CompilerMessages.BuildVerb}..."));
				ProjectService.RaiseEventBuildStarted(new BuildEventArgs(project, options));
				StartBuild(project, options,
				           new MessageViewSink(TaskService.BuildMessageViewCategory, progressMonitor, WorkbenchSingleton.StatusBar));
			}
		}
Exemplo n.º 24
0
Arquivo: Startup.cs Projeto: 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;
        }
Exemplo n.º 25
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 async void button1_Click(object sender, EventArgs e)
        {
            progressBarSample = new ProgressBarSample();
            progressBarSample.ProgressChanged += OnProgressChanged;
            cancellationTokenSource            = new System.Threading.CancellationTokenSource();
            var token = cancellationTokenSource.Token;

            string message = "";
            bool   isError = false;

            try
            {
                var task = await Task <bool> .Factory.StartNew(() => progressBarSample.Work(token), token);

                //await task;
            }
            catch (OperationCanceledException)
            {
            }
            catch (Exception ex)
            {
                isError = true;
                message = $"Произошла ошибка {ex.Message}";
            }

            if (!isError)
            {
                message = true ? "Процесс отменет" : "Процесс завершен";
            }

            MessageBox.Show(message);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Classe à utiliser dans les tâches, pour retourner une progression et permettre l'annulation, Ajouter dans les boucles une vérification de IsCancellationRequested
 /// </summary>
 /// <param name="iProgressAction">Action à executer lors d'une progression, ex : Action&lt;NotifierProgress&gt; progressAction = (value) => {textBox1.Text = value.ProgressCount + " " + value.Message; }; </param>
 public ProgressCancelNotifier(Action <NotifierProgress> iProgressAction, string iName = null)
 {
     CancellationTokenSource = new System.Threading.CancellationTokenSource();
     Name = iName;
     SetProgressAction(iProgressAction);
     Guid = new Guid().ToString();
 }
        public async Task SendMessage(WebSocket socket, string message)
        {
            System.Threading.CancellationTokenSource cancelationTokenSource = new System.Threading.CancellationTokenSource();
            ArraySegment <byte> buffer = new ArraySegment <byte>(System.Text.Encoding.ASCII.GetBytes(message.ToCharArray()));

            await socket.SendAsync(buffer, WebSocketMessageType.Text, true, cancelationTokenSource.Token);
        }
Exemplo n.º 29
0
 public Generator()
 {
     cancelSource = new CancellationTokenSource();
     cancelToken = cancelSource.Token;
     Stalled += StalledEventHandler;
     running = false;
 }
        public FetchedJobsWatcherFacts()
        {
            var options = new RedisStorageOptions() { Db = RedisUtils.GetDb() };
            _storage = new RedisStorage(RedisUtils.GetHostAndPort(), options);
			_cts = new CancellationTokenSource();
			_cts.Cancel();
        }
Exemplo n.º 31
0
    // Message per hour
    //const string TimeUnit = "h";
    //private readonly long TicksPerTimeUnit = Stopwatch.Frequency * 3600;

    public void Start()
    {
        Log.Info("Starting...");
        stopLoop = new CancellationTokenSource();
        loopTask = Task.Factory.StartNew(Loop, TaskCreationOptions.LongRunning);
        Log.Info("Started");
    }
Exemplo n.º 32
0
        private void UpdateData()
        {
            rootGrid.DataContext = null;
            // обновление данных согласно нового временного периода
            var cts = new System.Threading.CancellationTokenSource();

            var task = EmcosSiteWrapper.Instance.ExecuteAction(cts, () =>
            {
                //State = State.Busy;
                var substation = _balance.Substation.Copy() as Model.Balance.Substation;
                substation.ClearData();

                Utils.GetArchiveDataForSubstation(_balance.Period.StartDate, _balance.Period.EndDate, substation, cts, UpdateCallBack);

                foreach (Model.Balance.IBalanceItem i in substation.Items)
                {
                    i.SetSubstation(substation);
                }

                _balance.Initialize(_balance.Period);
                DispatcherExtensions.InUi(() =>
                {
                    Create_tableColumns();
                    rootGrid.DataContext = _balance;
                    table.ItemsSource    = _balance.Items;
                    //Progress = 0;
                });

                //State = State.Idle;
            });
        }
Exemplo n.º 33
0
        private static void ScheduleNewJob(Project proj)
        {
            var cts   = new System.Threading.CancellationTokenSource();
            var token = cts.Token;

            var jobInfo = CreateJob_DaylightFactor();

            //var jobInfo = CreateJob_AnnualDaylight();
            try
            {
                jobInfo.SetJobSubFolderPath("round1/test");
                jobInfo.SetJobName("A new daylight simulation");

                // run a job
                var task = jobInfo.RunJobOnCloud(proj, (s) => Console.WriteLine(s), token);

                //cts.CancelAfter(60000);
                var scheduledJob = task.Result;

                // watch status
                var watchTask = scheduledJob.WatchJobStatusAsync((s) => Console.WriteLine(s), token);
                watchTask.Wait();
                Console.WriteLine($"Canceled check: {token.IsCancellationRequested}");
                cts.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException.Message);
                //throw;
            }
        }
        public async Task Register(string user, WebSocket websocket)
        {
            WebSocket currentWebSocket;

            if (connections.TryGetValue(user, out currentWebSocket))
            {
                if (currentWebSocket.State == WebSocketState.CloseReceived)
                {
                    await currentWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Existing connection", CancellationToken.None)
                    .ContinueWith(a => currentWebSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Existing connection", CancellationToken.None))
                    .ContinueWith(a => Console.Write("closed connection"));

                    connections.Remove(user);
                }
                else
                {
                    var userConnection = connections[user];
                    System.Threading.CancellationTokenSource cancelationTokenSource = new System.Threading.CancellationTokenSource();
                    ArraySegment <byte> buffer = new ArraySegment <byte>(System.Text.Encoding.ASCII.GetBytes($"Ooops!This connection is already open under ID {userConnection.GetHashCode()} and its status is {userConnection.State}".ToCharArray()));
                    await userConnection.SendAsync(buffer, WebSocketMessageType.Text, true, cancelationTokenSource.Token).ContinueWith(task => Console.WriteLine("Message Sent"));
                }
            }
            else
            {
                connections.Add(user, websocket);
                await StartListening(user, websocket);
            }
        }
Exemplo n.º 35
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);
        }
Exemplo n.º 36
0
        public static T.CancellationToken ToTpl(this CancellationToken ct)
        {
            var cts = new T.CancellationTokenSource();

            ct.Register(() => cts.Cancel());
            return(cts.Token);
        }
Exemplo n.º 37
0
        internal void StopAll()
        {
            _reloadingCts.Cancel();
            var oldsrc = _reloadingCts;

            _reloadingCts = new System.Threading.CancellationTokenSource();
        }
        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();
            }
        }
Exemplo n.º 39
0
        public SimulatorForm()
        {
            InitializeComponent();

            this.SetStyle(
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.UserPaint |
                ControlStyles.DoubleBuffer, true);

            this.log = Log.Logger;

            this.updateActions = new List <Action>();
            this.cancelSource  = new System.Threading.CancellationTokenSource();
            this.senderTask    = new Task(x =>
            {
                while (!this.cancelSource.IsCancellationRequested)
                {
                    lock (this.updateActions)
                    {
                        foreach (var action in this.updateActions)
                        {
                            action();
                        }
                    }

                    System.Threading.Thread.Sleep(100);
                }
            }, this.cancelSource.Token, TaskCreationOptions.LongRunning);

            this.senderTask.Start();
        }
Exemplo n.º 40
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();
        }
Exemplo n.º 41
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");
        }
Exemplo n.º 42
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();
        }
        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;
                    });
                }
            }
        }
Exemplo n.º 44
0
        void loadFaceCallback(ICollection[] result, Exception ex)
        {
            if (ex != null)
            {
                MessageBox.Show(this, "系统发生异常,请重试。", this.Text);
                return;
            }

            _cts = new CancellationTokenSource();
            var worker = Task.Factory.StartNew(CompareFaces, result, _cts.Token);

            worker.ContinueWith(ant =>
            {
                if (ant.Exception != null)
                {
                    if (!(ant.Exception.InnerException is OperationCanceledException))
                    {
                        MessageBox.Show("系统发生异常,请重试。");
                    }
                }

                ShowCompareStatus(false);
                ShowCompareButton(true);
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
        /// <summary>
        ///     Specifies a path to directory where to save/load images.
        /// </summary>
        /// <param name="directory">
        ///     The path to directory with images.
        /// </param>
        /// <returns>
        ///     The instance of the loader.
        /// </returns>
        /// <remarks>
        ///     If the directory is not specified, i.e. <see cref="WithDirectory"/> is not called, then the default temp directory will be used.
        /// </remarks>
        public FileSystemImageLoader WithDirectory(string directory)
        {
            if (string.IsNullOrWhiteSpace(directory))
            {
                throw new ArgumentNullException("directory");
            }

            lock (this.indexSyncObject)
            {
                if (StringComparer.OrdinalIgnoreCase.Compare(this.directory, directory) != 0)
                {
                    EnsureDireactoryExist(directory);

                    if (this.updateIndexToken != null)
                    {
                        this.updateIndexToken.Cancel();
                    }

                    this.ClearIndex();

                    this.directory = directory;
                    this.updateIndexToken = new CancellationTokenSource();
                    this.UpdateIndexAsync(directory, this.updateIndexToken.Token);
                }
            }

            return this;
        }
Exemplo n.º 46
0
        public Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationTokenSource cancellationToken)
        {
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;

            var tcs = new TaskCompletionSource<ProcessResults>();

            var standardOutput = new List<string>();
            var standardError = new List<string>();

            var process = new Process
            {
                StartInfo = processStartInfo,
                EnableRaisingEvents = true
            };

            process.OutputDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardOutput.Add(args.Data);
                }
            };

            process.ErrorDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardError.Add(args.Data);
                }
            };

            
            cancellationToken.Token.ThrowIfCancellationRequested();

            _log.Debug("Registering cancellation for " + cancellationToken.GetHashCode());

            cancellationToken.Token.Register(() =>
            {
                tcs.TrySetCanceled();
                KillProcessAndChildren(process.Id);
            });


               process.Exited += (sender, args) =>
               {
                   tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError));
               };

            if (process.Start() == false)
            {
                tcs.TrySetException(new InvalidOperationException("Failed to start process"));
            }

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }
            public void Enable()
            {
                lock (_gate)
                {
                    if (_instanceTask != null)
                    {
                        // already enabled
                        return;
                    }

                    if (!_workspace.Options.GetOption(RemoteHostOptions.RemoteHost))
                    {
                        // not turned on
                        return;
                    }

                    var remoteHostClientFactory = _workspace.Services.GetService<IRemoteHostClientFactory>();
                    if (remoteHostClientFactory == null)
                    {
                        // dev14 doesn't have remote host client factory
                        return;
                    }

                    // make sure we run it on background thread
                    _shutdownCancellationTokenSource = new CancellationTokenSource();

                    var token = _shutdownCancellationTokenSource.Token;
                    _instanceTask = Task.Run(() => EnableAsync(token), token);
                }
            }
Exemplo n.º 48
0
        /// <summary>
        /// ファイルからドキュメントを構築する
        /// </summary>
        /// <param name="filepath">ファイルパス</param>
        /// <param name="enc">エンコード</param>
        /// <param name="token">キャンセル用トークン</param>
        /// <returns>Taskオブジェクト</returns>
        public async Task LoadFileAsync(string filepath, Encoding enc, System.Threading.CancellationTokenSource token)
        {
            var fs = new System.IO.StreamReader(filepath, enc);

            await this.Document.LoadAsync(fs, token);

            fs.Close();
        }
Exemplo n.º 49
0
        public Task Run(out System.Threading.CancellationTokenSource cts)
        {
            Task task;

            cts = Executor.Current.Execute(this, out task);

            return(task);
        }
Exemplo n.º 50
0
 private static CancellationTokenSource ResetCancellationTokenSource(System.Threading.CancellationTokenSource cts)
 {
     if (cts != null)
     {
         cts.Dispose();
     }
     // Create a new cancellation token source so that can cancel all the tokens again
     return(new CancellationTokenSource());
 }
Exemplo n.º 51
0
 public void Clear()
 {
     lock (queue)
     {
         CancellationTokenSource = new System.Threading.CancellationTokenSource();
         queue.Clear();
         Monitor.Pulse(queue);
     }
 }
Exemplo n.º 52
0
        public bool Enqueue(T item)
        {
            lock (queue)
            {
                if (this.Count > 0)
                {
                    var _item = queue.Dequeue();
                    if (_item.WaitForResponse)
                    {
                        L4Logger.Info("Can not insert item must WaitForResponse => " + _item.MethodName);
                        queue.Enqueue(_item);
                        item.Dispose();
                        return(false);
                    }
                    else
                    {
                    }
                }
                if (closing || null == item)
                {
                    return(false);
                }

                queue.Enqueue(item);
                CancellationTokenSource?.Dispose();
                CancellationTokenSource = new System.Threading.CancellationTokenSource();
                System.Threading.Tasks.Task.Run(async delegate
                {
                    await Task.Delay(item.CommandTimeSpan, CancellationTokenSource.Token);

                    if (!CancellationTokenSource.IsCancellationRequested)
                    {
                        if (ObjectTimeout != null)
                        {
                            if (queue.Count > 0)
                            {
                                var value = (T)queue.Dequeue();
                                L4Logger.Info(string.Format("object Dequeue Timeout method {0} guid {1} ", value.MethodName, value.guid));
                                value.Dispose();
                                ObjectTimeout.Invoke(value);
                            }
                        }
                    }
                });

                L4Logger.Info(string.Format("item inserted  {0}  Timeout  {1}  WaitForResponse {2}  guid {3}",
                                            item.MethodName, item.CommandTimeSpan, item.WaitForResponse, item.guid));

                if (queue.Count == 1)
                {
                    // wake up any blocked dequeue
                    Monitor.PulseAll(queue);
                }
                item = null;
                return(true);
            }
        }
Exemplo n.º 53
0
        /// <summary>
        /// ドキュメントの内容をファイルに保存する
        /// </summary>
        /// <param name="filepath">ファイルパス</param>
        /// <param name="newLine">改行コード</param>
        /// <param name="enc">エンコード</param>
        /// <param name="token">キャンセル用トークン</param>
        /// <returns>Taskオブジェクト</returns>
        public async Task SaveFile(string filepath, Encoding enc, string newLine, System.Threading.CancellationTokenSource token)
        {
            var fs = new System.IO.StreamWriter(filepath, false, enc);

            fs.NewLine = newLine;
            await this.Document.SaveAsync(fs, token);

            fs.Close();
        }
Exemplo n.º 54
0
        protected override void OnConnected(bool bSuccess, string strErrors)
        {
            try
            {
                if ((bSuccess == true) && (Client.Connected == true))
                {
                    this.Client.NoDelay = true;

#if !WINDOWS_PHONE
                    this.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, Windows.Networking.Sockets.SocketOptionName.KeepAlive, true);
#endif
#if WINDOWS_PHONE
                    var cancellationTokenSource = new System.Threading.CancellationTokenSource();
                    var task = Repeat.Interval(
                        TimeSpan.FromSeconds(60),
                        () => OnKeepAlive(),
                        cancellationTokenSource.Token
                        );
                    //  this.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, Windows.Networking.Sockets.SocketOptionName.KeepAlive, true);
#endif

                    XMPPClient.XMPPState = XMPPState.Connected;
                    XMPPClient.FireConnectAttemptFinished(true);
                    System.Diagnostics.Debug.WriteLine(string.Format("Successful TCP connection"));
                }
                else
                {
                    XMPPClient.XMPPState = XMPPState.Unknown;
                    XMPPClient.FireConnectAttemptFinished(false);
                    System.Diagnostics.Debug.WriteLine(string.Format("Failed to connect: {0}", strErrors));
                    return;
                }

                if (XMPPClient.UseOldStyleTLS == true)
                {
                    StartTLS();
                }


                /// Send stream header if we haven't yet
                XMPPClient.XMPPState = XMPPState.Authenticating;

                OpenStreamStanza open    = new OpenStreamStanza(this.XMPPClient);
                string           strSend = open.XML;
                byte[]           bStanza = System.Text.UTF8Encoding.UTF8.GetBytes(strSend);
                this.Send(bStanza);
            }
            catch (TimeoutException tx)
            {
                Console.WriteLine(tx.InnerException.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 55
0
        /// <summary>
        /// Classe à utiliser dans les tâches, pour retourner une progression et permettre l'annulation. Ajouter dans les boucles une vérification de IsCancellationRequested. Action de progression est par défaut une ligne en débug.
        /// </summary>
        public ProgressCancelNotifier(string iName = null)
        {
            CancellationTokenSource = new System.Threading.CancellationTokenSource();
            Name = iName;
            //Action<NotifierProgress> theAction = (NotifierProgress iProgress) => { };

            Action <NotifierProgress> theAction = (value) => { MyDebug.PrintInformation(value); };

            SetProgressAction(theAction);
            Guid = System.Guid.NewGuid().ToString();
        }
Exemplo n.º 56
0
        public Button(InputPinConfiguration outputPin, IGpioConnectionDriver driver = null)
        {
            PinConfig = outputPin;
            Driver    = driver ?? GpioConnectionSettings.DefaultDriver;
            Driver.Allocate(PinConfig.Pin, PinDirection.Output);
            TokenScource = new System.Threading.CancellationTokenSource();
            Action a = Watch;

            Task.Run(a, TokenScource.Token);
            // Task.Start(Watch);
        }
Exemplo n.º 57
0
 /// <summary>
 ///  <c>Dispose</c>パターンによる実装.
 /// </summary>
 /// <param name="disposing"><c>Dispose()</c>から呼ばれたかどうかを示す</param>
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (this.cancellationTokenSource != null)
         {
             this.cancellationTokenSource.Dispose();
             this.cancellationTokenSource = null;
         }
     }
 }
Exemplo n.º 58
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();
        }
Exemplo n.º 59
0
        public void Cancel(bool isInner = false)
        {
            AcioningItems.Remove(this);
            if (_targetModel.ResourceModel.Progress > 0.98)
            {
                AppData.MainMV.TipMessage = "视频消息已发出无法取消!";
                return;
            }
            if (ChatViewModel != null)
            {
                if (_operateTask != null)
                {
                    _operateTask.Cancel();
                    _operateTask = null;

                    if (isInner)
                    {
                        return;
                    }
                }

                string tip = _targetModel.Sender.ID == AppData.Current.LoginUser.ID ? "发送" : "接收";

                string size = Helper.FileHelper.FileSizeToString(_targetModel.ResourceModel.Length);
                string msg  = $"您取消了\"{_targetModel.ResourceModel.FileName}\"({size})的{tip},文件传输失败。";

                _targetModel.MsgType      = MessageType.notification;
                _targetModel.MessageState = MessageStates.Fail;
                _targetModel.Content      = msg;

                ChatViewModel.UpdateMsg(_targetModel);

                int roomID = ChatViewModel.Model.ID;

                var chatType = ChatViewModel.IsGroup ? SDKClient.SDKProperty.chatType.groupChat : SDKClient.SDKProperty.chatType.chat;

                Task.Run(async() =>
                         await SDKClient.SDKClient.Instance.AppendLocalData_NotifyMessage(AppData.Current.LoginUser.ID.ToString(), roomID.ToString(),
                                                                                          msg, roomID, SDKClient.SDKProperty.MessageType.notification, chatType: chatType));
                if (this.FileState == FileStates.SendOnline ||
                    _targetModel.ResourceModel.RefInfo is SDKClient.Model.OnlineFileBody body) //在线消息会发送取消给对方
                {
                    SDKClient.SDKProperty.chatType messageType = ChatViewModel.IsGroup ? SDKClient.SDKProperty.chatType.groupChat : SDKClient.SDKProperty.chatType.chat;
                    SDKClient.SDKClient.Instance.SendRetractMessage(_targetModel.MsgKey, ChatViewModel.ID.ToString(), messageType, ChatViewModel.IsGroup ? ChatViewModel.ID : 0, SDKClient.SDKProperty.RetractType.SourceEndOnlineRetract);
                }
                else //离线消息不发送
                {
                    _targetModel.Sender = null;
                    SDKClient.SDKClient.Instance.CancelOfflineFileRecv(_targetModel.MsgKey);
                }
                _targetModel.ResourceModel.FileState = FileStates.Fail;
            }
        }
Exemplo n.º 60
0
        private CancellationToken GetCancellationToken()
        {
            lock (_lock)
            {
                if (_cancellationTokenSource is null)
                {
                    _cancellationTokenSource = new CancellationTokenSource();
                }

                return(_cancellationTokenSource.Token);
            }
        }