Ejemplo n.º 1
0
        public bool WriteTxt(string txtPath, string searchTxt, string path)
        {
            if (Token.IsCancellationRequested)
            {
                return(false);
            }
            var fileName = Path.GetFileName(path);

            if (fileName != null && fileName.Equals(searchTxt))
            {
                using (var tw = new StreamWriter(txtPath, true))
                {
                    tw.WriteLine(Environment.NewLine + "Gefunden: " + path);
                    // Global Variable begin
                    FoundTargetPath = path;
                    tw.WriteLine(Environment.NewLine + "Text :" + ReadTxt());
                    // Global Variable end
                    CancelTokenSource.Cancel();
                    return(true);
                }
            }
            using (var tw = new StreamWriter(txtPath, true))
            {
                tw.WriteLine(path);
                return(false);
            }
        }
Ejemplo n.º 2
0
 private void StartInputActionTask()
 {
     CancelTokenSource?.Cancel();
     CancelTokenSource = new CancellationTokenSource();
     CancelToken       = CancelTokenSource.Token;
     InputActionsTask  = Task.Run(CheckQueue, CancelTokenSource.Token);
 }
        /// <summary>
        /// Removes the item from the queue. If the item is currently being processed, the task
        /// is cancelled.
        /// </summary>
        /// <param name="mediaQueueId">The media queue ID.</param>
        public void RemoveMediaQueueItem(int mediaQueueId)
        {
            MediaQueueItem item;

            if (MediaQueueItemDictionary.TryGetValue(mediaQueueId, out item))
            {
                MediaQueueItem currentItem = GetCurrentMediaQueueItem();
                if ((currentItem != null) && (currentItem.MediaQueueId == mediaQueueId))
                {
                    CancelTokenSource.Cancel();

                    if (Task != null)
                    {
                        Task.Wait(20000);                         // Wait up to 20 seconds
                    }

                    Instance.Status = MediaQueueStatus.Idle;
                }

                //Factory.GetDataProvider().MediaQueue_Delete(item);
                item.Delete();

                MediaQueueItemDictionary.TryRemove(mediaQueueId, out item);
            }
        }
Ejemplo n.º 4
0
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            CancelTokenSource.Cancel();

            Log("Cancelling...");
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
        }
 /// <summary>
 /// Deinit driver communiation - means autorefresh of the messages
 /// </summary>
 /// <returns></returns>
 public override async Task DeInit()
 {
     if (CancelToken != null)
     {
         CancelTokenSource.Cancel();
     }
 }
Ejemplo n.º 6
0
        public override void Stop(bool waitForQueueToDrain)
        {
            stopping = true;

            //See if we want to wait for the queue to drain before stopping
            if (waitForQueueToDrain)
            {
                while (QueuedNotificationCount > 0 || sentNotifications.Count > 0)
                {
                    Thread.Sleep(50);
                }
            }

            //Sleep a bit to prevent any race conditions
            //especially since our cleanup method may need 3 seconds
            Thread.Sleep(5000);

            if (!CancelTokenSource.IsCancellationRequested)
            {
                CancelTokenSource.Cancel();
            }

            //Wait on our tasks for a maximum of 30 seconds
            Task.WaitAll(new Task[] { base.taskSender, taskCleanup }, 30000);
        }
Ejemplo n.º 7
0
        } // end of function - StartReader

        /*======================= PROTECTED =====================================*/
        /************************ Events *****************************************/
        /************************ Properties *************************************/
        /************************ Construction ***********************************/
        /************************ Methods ****************************************/
        /// <summary>
        /// Explicit dispose method
        /// </summary>
        /// <param name="disposing">
        /// Are we explicitly disposing, or called from the destructor
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            if (!CancelTokenSource.IsCancellationRequested)
            {
                CancelTokenSource.Cancel();
            } // end of if - cancel has not already be requested
            try
            {
#warning Should revisit this wait on the data reader
                DataReader.Wait(4000);
            }
            catch (Exception)
            {
                // Nothing to do with this exception at this point
            }

            if (disposing)
            {
                if (CloseStream && null != BaseStream)
                {
                    BaseStream.Close();
                    BaseStream.Dispose();
                } // end of if - we should close the base stream
                CancelTokenSource.Dispose();
            }     // end of if - explicitly disposing
            BaseStream        = null;
            CancelTokenSource = null;
        } // end of function - Dispose
Ejemplo n.º 8
0
        private void StartInputProcessingThread()
        {
            try
            {
                CancelTokenSource?.Cancel();
                CancelTokenSource?.Dispose();
            }
            catch { }

            // After BlockInput is enabled, only simulated input coming from the same thread
            // will work.  So we have to start a new thread that runs continuously and
            // processes a queue of input events.
            _inputProcessingThread = new Thread(() =>
            {
                Logger.Write($"New input processing thread started on thread {Thread.CurrentThread.ManagedThreadId}.");
                CancelTokenSource = new CancellationTokenSource();

                if (_inputBlocked)
                {
                    ToggleBlockInput(true);
                }
                CheckQueue(CancelTokenSource.Token);
            });

            _inputProcessingThread.SetApartmentState(ApartmentState.STA);
            _inputProcessingThread.Start();
        }
Ejemplo n.º 9
0
        public override void Stop(bool waitForQueueToDrain)
        {
            stopping = true;

            //See if we want to wait for the queue to drain before stopping
            if (waitForQueueToDrain)
            {
                var sentNotificationCount = 0;
                lock (sentLock)
                    sentNotificationCount = sentNotifications.Count;

                while (QueuedNotificationCount > 0 || sentNotificationCount > 0 || Interlocked.Read(ref trackedNotificationCount) > 0)
                {
                    Thread.Sleep(100);

                    lock (sentLock)
                        sentNotificationCount = sentNotifications.Count;
                }
            }

            if (!CancelTokenSource.IsCancellationRequested)
            {
                CancelTokenSource.Cancel();
            }

            //Wait on our tasks for a maximum of 5 seconds
            Task.WaitAll(new Task[] { base.taskSender, taskCleanup }, 5000);
        }
Ejemplo n.º 10
0
        /// <inheritdoc />
        public Task StopHandlingNetworkClient()
        {
            isNetworkHandling = false;

            CancelTokenSource.Cancel();
            //TODO: Should we await for the dispatch thread to actually end??

            return(Task.CompletedTask);
        }
Ejemplo n.º 11
0
 public virtual void StopTask()
 {
     if (!TaskRunning)
     {
         return;
     }
     CancelTokenSource?.Cancel();
     Wait?.Set();
 }
Ejemplo n.º 12
0
        private void DisposeCancelToken()
        {
            if (CancelTokenSource == null)
            {
                return;
            }

            CancelTokenSource.Dispose();
            CancelTokenSource = null;
        }
Ejemplo n.º 13
0
        private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            e.Cancel = true;

            foreach (var shard in Shards)
            {
                shard.StopAsync().GetAwaiter().GetResult(); // it dun matter
            }
            CancelTokenSource.Cancel();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates a new webmedia client with the given IP, Port, and HTTP server
        /// </summary>
        /// <param name="ip">The IP of the webmedia link server</param>
        /// <param name="port">The port of the webmedia link server</param>
        /// <param name="httpIp">The IP to host the HTTP server from</param>
        /// <param name="httpPort">The port to host the HTTP server on</param>
        /// <param name="name">The name of the media server</param>
        /// <param name="password">The password of the media server</param>
        /// <param name="pathToMediaFiles">The location of the folder containing the media files</param>
        /// <param name="pathToDownloadFiles">The location of the folder containing the download files</param>
        /// <param name="pathToSubtitleFiles">The location of the folder containing the subtitle files</param>
        public WebMediaClient(string ip, ushort port, string httpIp, ushort httpPort, string name, string password, string pathToMediaFiles, string pathToDownloadFiles, string pathToSubtitleFiles)
        {
            WebserverIp       = ip;
            WebserverPort     = port;
            MediaserverIp     = httpIp;
            MediaserverPort   = httpPort;
            Name              = name;
            Password          = password;
            MediaFilesPath    = pathToMediaFiles;
            DownloadFilesPath = pathToDownloadFiles;
            SubtitleFilesPath = pathToSubtitleFiles;

            //Use the .exe if windows, use the . nothing otherwise
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                Downloader = new YoutubeDL(Helpful.GetExecutingDirectory() + "\\youtubedl.exe", CancelToken);
            }
            else
            {
                Downloader = new YoutubeDL(Helpful.GetExecutingDirectory() + "\\youtubedl", CancelToken);
            }

            //Create the media server
            MediaServer = new HttpServer(httpIp, httpPort, pathToMediaFiles, pathToDownloadFiles, pathToSubtitleFiles, CancelTokenSource.Token);

            //Populate the media server's list of available files
            RescanForFiles();

            //Try to start media server. If it fails, stop the program
            if (!MediaServer.StartServer())
            {
                CancelTokenSource.Cancel();
                ConLog.Log("HTTP Server", "Failed to start HTTP server. Try running as an administrator, and check that your firewall or antivirus isn't preventing this program from starting the HTTP server", LogType.Fatal);
            }

            //Register file system watchers
            FileSystemWatcher mediaWatcher = new FileSystemWatcher(pathToMediaFiles, "*.*");

            mediaWatcher.EnableRaisingEvents   = true;
            mediaWatcher.IncludeSubdirectories = false;
            mediaWatcher.Changed += (sender, e) => UpdateAvailableFiles();
            mediaWatcher.Created += (sender, e) => UpdateAvailableFiles();
            mediaWatcher.Deleted += (sender, e) => UpdateAvailableFiles();
            mediaWatcher.Renamed += (sender, e) => UpdateAvailableFiles();
            FileSystemWatcher downloadWatcher = new FileSystemWatcher(pathToDownloadFiles, "*.*");

            downloadWatcher.EnableRaisingEvents   = true;
            downloadWatcher.IncludeSubdirectories = false;
            downloadWatcher.Changed += (sender, e) => UpdateAvailableFiles();
            downloadWatcher.Created += (sender, e) => UpdateAvailableFiles();
            downloadWatcher.Deleted += (sender, e) => UpdateAvailableFiles();
            downloadWatcher.Renamed += (sender, e) => UpdateAvailableFiles();
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Stop the data processor async task
        /// </summary>
        public async Task StopRealTimeProcessingAsyncAsync()
        {
            if (CancelTokenSource != null)
            {
                CancelTokenSource.Cancel();
                await MonitorRunTask;

                CancelTokenSource = null;
                MonitorRunTask    = null;

                Log?.Invoke(this, new LogEventArgs(Name, this, "StopMonitorAsync", $"Stopped signal filtering for {Name}.", LogLevel.INFO));
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Stop the data processor async task
        /// </summary>
        public async Task StopDetectorAsync()
        {
            if (CancelTokenSource != null)
            {
                CancelTokenSource.Cancel();
                await RunTask;

                CancelTokenSource = null;
                RunTask           = null;
            }

            Log?.Invoke(this, new LogEventArgs(this, "StopDetectorAsync", $"Stopped alpha wave detector.", LogLevel.INFO));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Stop the data processor async task
        /// </summary>
        public async Task StopMonitorAsync()
        {
            if (CancelTokenSource != null)
            {
                CancelTokenSource.Cancel();
                await MonitorRunTask;

                CancelTokenSource = null;
                MonitorRunTask    = null;

                Log?.Invoke(this, new LogEventArgs(Name, this, "StopMonitorAsync", $"Stopped band power monitor for {Name}.", LogLevel.INFO));
            }
        }
Ejemplo n.º 18
0
 public Task <bool> RunAsConsole()
 {
     Console.WriteLine("Making chat-sender...");
     while (!CancelTokenSource.Token.IsCancellationRequested)
     {
         var message = Console.ReadLine();
         SendMessage(message);
         if (message == "!quit" || message == "!exit")
         {
             CancelTokenSource.Cancel();
         }
     }
     return(Task.FromResult(true));
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Stop status monitor
        /// </summary>
        public async Task StopStatusMonitorAsync()
        {
            if (CancelTokenSource != null)
            {
                CancelTokenSource.Cancel();
                if (RunTask != null)
                {
                    await RunTask;
                }

                CancelTokenSource = null;
                RunTask           = null;
            }
        }
Ejemplo n.º 20
0
        private void DisposeCancelToken()
        {
            if (Interlocked.Decrement(ref _activeAsyncRequests) > 0)
            {
                return;
            }
            if (CancelTokenSource == null)
            {
                return;
            }

            CancelTokenSource.Dispose();
            CancelTokenSource = null;
        }
        /// <summary>
        /// Stop data broadcast server
        /// </summary>
        public async Task StopDataBroadcastServerAsync()
        {
            if (CancelTokenSource != null)
            {
                CancelTokenSource.Cancel();
                if (RunTask != null)
                {
                    await RunTask;
                }

                CancelTokenSource = null;
                RunTask           = null;
            }
        }
Ejemplo n.º 22
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             CancelTokenSource?.Cancel();
             ComparerTask?.Wait();
             CancelTokenSource?.Dispose();
             ComparerTask?.Dispose();
             LeftVideoFile?.Dispose();
             RightVideoFile?.Dispose();
         }
         disposedValue = true;
     }
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Stop the broadcaster and close the outlet
        /// </summary>
        /// <returns></returns>
        public async Task StopLslBroadcastAsync()
        {
            if (CancelTokenSource != null)
            {
                CancelTokenSource.Cancel();
                if (RunTask != null)
                {
                    await RunTask;
                }

                CancelTokenSource = null;
                RunTask           = null;
            }

            DataToBroadcast.RemoveAll();
        }
Ejemplo n.º 24
0
        protected virtual void Dispose(bool safe)
        {
            if (safe)
            {
                if (videoRender != null)
                {
                    videoRender.Dispose();
                    videoRender = null;
                }
                if (audioPlayer != null)
                {
                    audioPlayer.Dispose();
                    audioPlayer = null;
                }
                if (videoDecoder != null)
                {
                    videoDecoder.Dispose();
                    videoDecoder = null;
                }

                /*if (demuxPacketsTask != null)
                 * {
                 *  demuxPacketsTask.Dispose();
                 *  demuxPacketsTask = null;
                 * }*/
                if (CancelTokenSource != null)
                {
                    CancelTokenSource.Dispose();
                    CancelTokenSource = null;
                }
                if (demuxPacketsCancellationTokenSource != null)
                {
                    demuxPacketsCancellationTokenSource.Dispose();
                    demuxPacketsCancellationTokenSource = null;
                }
                if (videoRefreshTimer != null)
                {
                    videoRefreshTimer.Dispose();
                    videoRefreshTimer = null;
                }
                if (audioRefreshTimer != null)
                {
                    audioRefreshTimer.Dispose();
                    audioRefreshTimer = null;
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Stop the board reader process
        /// </summary>
        public async Task StopBoardDataReaderAsync()
        {
            if (CancelTokenSource != null)
            {
                Log?.Invoke(this, new LogEventArgs(this, "StopBoardDataReaderAsync", $"Stopping board data reader", LogLevel.DEBUG));

                CancelTokenSource.Cancel();
                if (RunTask != null)
                {
                    await RunTask;
                }

                CancelTokenSource = null;
                RunTask           = null;

                await ReleaseBoardAsync();
            }
        }
Ejemplo n.º 26
0
        public void ToggleBlockInput(bool toggleOn)
        {
            InputActions.Enqueue(() =>
            {
                _inputBlocked = toggleOn;
                var result    = BlockInput(toggleOn);
                Logger.Write($"Result of ToggleBlockInput set to {toggleOn}: {result}");

                if (!toggleOn)
                {
                    CancelTokenSource.Cancel();
                }
            });

            if (toggleOn)
            {
                StartInputProcessingThread();
            }
        }
Ejemplo n.º 27
0
        private void StartInputProcessingThread()
        {
            CancelTokenSource?.Cancel();
            CancelTokenSource?.Dispose();

            var newThread = new Thread(() =>
            {
                Logger.Write($"New input processing thread started on thread {Thread.CurrentThread.ManagedThreadId}.");
                CancelTokenSource = new CancellationTokenSource();
                if (inputBlocked)
                {
                    ToggleBlockInput(true);
                }
                CheckQueue(CancelTokenSource.Token);
            });

            newThread.SetApartmentState(ApartmentState.STA);
            newThread.Start();
        }
        public CannotCloseDialogViewModel() : base("", false, false)
        {
            Global           = Locator.Current.GetService <Global>();
            OperationMessage = "Dequeuing coins...Please wait";
            var canCancel = this.WhenAnyValue(x => x.IsBusy);
            var canOk     = this.WhenAnyValue(x => x.IsBusy, (isbusy) => !isbusy);

            OKCommand = ReactiveCommand.CreateFromTask(
                async() =>
            {
                CancelTokenSource.Cancel();
                while (!Initialization.IsCompleted)
                {
                    await Task.Delay(300);
                }

                // OK pressed.
                Close(false);
            },
                canOk);

            CancelCommand = ReactiveCommand.CreateFromTask(
                async() =>
            {
                OperationMessage = "Cancelling...Please wait";
                CancelTokenSource.Cancel();
                while (!Initialization.IsCompleted)
                {
                    await Task.Delay(300);
                }

                // OK pressed.
                Close(false);
            },
                canCancel);

            Observable
            .Merge(OKCommand.ThrownExceptions)
            .Merge(CancelCommand.ThrownExceptions)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex => Logger.LogError(ex));
        }
Ejemplo n.º 29
0
            public string SendMessage(string msg)
            {
                var formattedTimeString = DateTime.Now.ToString("HH':'mm':'ss");

                try
                {
                    Chat.K++;
                    ChatSpace.Put(Chat.K, formattedTimeString, LoggedInUser, msg);
                }
                catch (SocketException ex)
                {
                    Console.WriteLine(ex.Message);
                    CancelTokenSource.Cancel();
                    return(string.Empty);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return(FormatMessage(LoggedInUser, msg));
            }
Ejemplo n.º 30
0
        /// <summary>
        /// Stop the data processor async task, and all component processor tasks
        /// </summary>
        public async Task StopDataProcessorAsync(bool flush = false)
        {
            FlushQueue = flush;

            if (CancelTokenSource != null)
            {
                await StopRealTimeSignalProcessingAsync();

                await BandPowers.StopMonitorAsync();

                CancelTokenSource.Cancel();
                await Task.WhenAll(RawDataQueueProcessorTask, DataMonitorTask, PeriodicProcessorTask);

                CancelTokenSource         = null;
                RawDataQueueProcessorTask = null;
                PeriodicProcessorTask     = null;
                DataMonitorTask           = null;

                Log?.Invoke(this, new LogEventArgs(Name, this, "StopDataProcessor", $"Stopped Brainflow data processor for {Name}.", LogLevel.INFO));
            }
        }