Beispiel #1
0
        public PersistanceService()
        {
            WorkerThread = new Thread(async() =>
            {
                while (true)
                {
                    // In case the bot crashed and we have files that are not accounted for
                    foreach (string filePath in Directory.EnumerateFiles(mp3Directory))
                    {
                        if (!Files.Values.Contains(filePath))
                        {
                            var createdAt = File.GetCreationTime(filePath);
                            if ((DateTime.Now - createdAt).Hours >= 4)
                            {
                                await Task.Run(() => File.Delete(filePath));
                                continue;
                            }

                            Files.TryAdd(createdAt, filePath);
                        }
                    }

                    if (!Files.IsEmpty)
                    {
                        foreach (var time in Files.Keys)
                        {
                            if ((DateTime.Now - time).Hours >= 4)
                            {
                                if (Files.TryRemove(time, out string path))
                                {
                                    await Task.Run(() => { if (File.Exists(path))
                                                           {
                                                               File.Delete(path);
                                                           }
                                                   });
                                }
                            }
                        }
                    }

                    await Task.Delay(TimeSpan.FromMinutes(30.0));
                }
            })
            {
                IsBackground = true,
                Name         = "MusicBot Persistancy"
            };

            if (!Directory.Exists(mp3Directory))
            {
                Directory.CreateDirectory(mp3Directory);
            }

            WorkerThread.Start();
        }

        ~PersistanceService() => WorkerThread.Abort();
Beispiel #2
0
        /// <summary>
        /// Handles the Closing event of the GlassWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        private void GlassWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _parsing = true;
            ParserTimer.Stop();

            if (WorkerThread != null && WorkerThread.IsAlive)
            {
                try { WorkerThread.Abort(); } catch { }
            }
        }
Beispiel #3
0
 public void Abort()
 {
     try {
         if (WorkerThread == null)
         {
             return;
         }
         WorkerThread.Abort();
         WorkerThread.Join(50);
     } catch { }
     WorkerThread = null;
 }
Beispiel #4
0
        /// <summary>
        /// Stop this thread.
        /// </summary>
        /// <param name="join">Wait for the thread exit.</param>
        /// <param name="force">Force the thread exit.</param>
        public void Stop(bool join = false, bool force = false)
        {
            Running = false;

            if (force)
            {
                WorkerThread.Abort();
            }

            if (join)
            {
                WorkerThread.Join();
            }
        }
 public void ResetBot()
 {
     Worker.ProductIndex = -1;
     Worker.ProxyIndex   = -1;
     if (Worker.WorkerThreads.Count > 0)
     {
         foreach (Thread WorkerThread in Worker.WorkerThreads)
         {
             WorkerThread.Abort();
         }
         Worker.WorkerThreads.Clear();
     }
     ActiveBots          = "0";
     StartButton.Content = "Start";
     CurrentStatus       = "Stopped";
 }
        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            if (((Button)sender).Content.ToString() == "Start")
            {
                Worker.ResultsFile = "Results\\" + DateTime.Now.ToString("dddd, dd MMMM yyyy HH-mm-ss") + ".txt";
                if (!Directory.Exists("Results"))
                {
                    Directory.CreateDirectory("Results");
                }

                Worker.ProductIndex = -1;
                Worker.ProxyIndex   = -1;

                Task.Factory.StartNew(delegate
                {
                    Worker.WorkerThreads.Add(new Thread(Worker.UpdateActiveThreads));
                    Worker.WorkerThreads[0].Name         = "Active Bots";
                    Worker.WorkerThreads[0].IsBackground = true;
                    for (int i = 1; i <= Worker.ThreadCount; i++)
                    {
                        Worker.WorkerThreads.Add(new Thread(Worker.CheckProducts));
                        Worker.WorkerThreads[i].Name         = "Worker " + i;
                        Worker.WorkerThreads[i].IsBackground = true;
                        Worker.WorkerThreads[i].Start();
                    }
                }).Wait();
                Worker.WorkerThreads[0].Start();
                ((Button)sender).Content = "Pause";
                CurrentStatus            = "Working";
            }
            else
            {
                foreach (Thread WorkerThread in Worker.WorkerThreads)
                {
                    WorkerThread.Abort();
                }
                Worker.WorkerThreads.Clear();
                ActiveBots = "0";
                ((Button)sender).Content = "Start";
                CurrentStatus            = "Stopped";
            }
        }
Beispiel #7
0
 /// <summary>
 /// Checks for locked worker threads and removes any which are locked.
 /// A worker thread is considered locked if a task does not finish within
 /// WorkerThreadTaskProcessTimeoutSeconds seconds.
 /// </summary>
 private void _checkForLockedWorkerThreads()
 {
     for (int i = 0; i < _workers.Count; i++)
     {
         WorkerThread worker = null;
         try {
             worker = _workers.ElementAt(i);
         } catch (Exception e) { }
         if (worker == null)
         {
             break;
         }
         if (worker.CurrentTaskProcessTime() > WorkerThreadTaskProcessTimeoutSeconds * 1000)
         {
             _log("Warning: worker thread is locked");
             _workers.Remove(worker);
             worker.Abort();
         }
     }
 }
 void IAsyncDataAdapter.Cancel()
 {
     using (LogFactory.Instance.GetCurrentMethodLog())
     {
         _isCommandCancelled = true;
         if (_thread != null)
         {
             _thread.Stop();
             if (_provider.IsCommandCancelable)
             {
                 ThreadPool.QueueUserWorkItem(CancelWaitCallback);
             }
             else
             {
                 var joined = _thread.Join(5000);
                 if (!joined)
                 {
                     _thread.Abort();
                 }
             }
         }
     }
 }
Beispiel #9
0
        public QueueService()
        {
            WorkerThread = new Thread(() =>
            {
                while (true)
                {
                    if (Program.Queue.IsEmpty)
                    {
                        Thread.Sleep(500);
                        continue;
                    }

                    if (Program.Queue.TryDequeue(out Song song))
                    {
                        MusicBot.Commands.Skip.Reset();
                        Task.Run(async() => {
                            await Program.Instance.Audio.SendAudio(song, Program.Connection);
                        });
                        Thread.Sleep(5);
                    }

                    while (!Program.Instance.Audio.Stopped)
                    {
                        Thread.Sleep(100);
                    }

                    Thread.Sleep(1000);
                }
            })
            {
                IsBackground = true,
                Name         = "MusicBot Queue"
            };
            WorkerThread.Start();
        }

        ~QueueService() => WorkerThread.Abort();
 public static void StopWatchingLogFile()
 {
     WorkerThread.Abort();
     Trace.WriteLine("stop watch");
 }
Beispiel #11
0
        static bool DownloadDependencies(string RootPath, IEnumerable <DependencyFile> RequiredFiles, IEnumerable <DependencyBlob> Blobs, IEnumerable <DependencyPack> Packs, int NumThreads, int MaxRetries, string ProxyUrl)
        {
            // Make sure we can actually open the right number of connections
            ServicePointManager.DefaultConnectionLimit = NumThreads;

            // Build a lookup for the files that need updating from each blob
            Dictionary <string, List <DependencyFile> > BlobToFiles = new Dictionary <string, List <DependencyFile> >();

            foreach (DependencyFile RequiredFile in RequiredFiles)
            {
                List <DependencyFile> FileList;
                if (!BlobToFiles.TryGetValue(RequiredFile.Hash, out FileList))
                {
                    FileList = new List <DependencyFile>();
                    BlobToFiles.Add(RequiredFile.Hash, FileList);
                }
                FileList.Add(RequiredFile);
            }

            // Find all the required blobs
            DependencyBlob[] RequiredBlobs = Blobs.Where(x => BlobToFiles.ContainsKey(x.Hash)).ToArray();

            // Build a lookup for the files that need updating from each blob
            Dictionary <string, List <DependencyBlob> > PackToBlobs = new Dictionary <string, List <DependencyBlob> >();

            foreach (DependencyBlob RequiredBlob in RequiredBlobs)
            {
                List <DependencyBlob> BlobList = new List <DependencyBlob>();
                if (!PackToBlobs.TryGetValue(RequiredBlob.PackHash, out BlobList))
                {
                    BlobList = new List <DependencyBlob>();
                    PackToBlobs.Add(RequiredBlob.PackHash, BlobList);
                }
                BlobList.Add(RequiredBlob);
            }

            // Find all the required packs
            DependencyPack[] RequiredPacks = Packs.Where(x => PackToBlobs.ContainsKey(x.Hash)).ToArray();

            // Get temporary filenames for all the files we're going to download
            Dictionary <DependencyPack, string> DownloadFileNames = new Dictionary <DependencyPack, string>();

            foreach (DependencyPack Pack in RequiredPacks)
            {
                DownloadFileNames.Add(Pack, Path.GetTempFileName());
            }

            // Setup the async state
            AsyncDownloadState State = new AsyncDownloadState();

            State.NumFiles = RequiredFiles.Count();
            long NumBytesTotal = RequiredPacks.Sum(x => x.CompressedSize);
            ConcurrentQueue <DependencyPack> DownloadQueue   = new ConcurrentQueue <DependencyPack>(RequiredPacks);
            ConcurrentQueue <DependencyPack> DecompressQueue = new ConcurrentQueue <DependencyPack>();

            // Create all the worker threads
            Thread[] WorkerThreads = new Thread[NumThreads];
            for (int Idx = 0; Idx < NumThreads; Idx++)
            {
                WorkerThreads[Idx] = new Thread(x => DownloadWorker(RootPath, DownloadQueue, DecompressQueue, DownloadFileNames, PackToBlobs, BlobToFiles, State, MaxRetries, ProxyUrl));
                WorkerThreads[Idx].Start();
            }

            // Create the decompression thread
            Thread DecompressionThread = new Thread(x => DecompressWorker(RootPath, DecompressQueue, DownloadFileNames, PackToBlobs, BlobToFiles, State));

            DecompressionThread.Start();

            // Tick the status message until we've finished or ended with an error. Use a circular buffer to average out the speed over time.
            long[] NumBytesReadBuffer = new long[60];
            for (int BufferIdx = 0, NumFilesReportedRead = 0; NumFilesReportedRead < State.NumFiles && State.NumFailingDownloads < NumThreads && State.LastDecompressError == null; BufferIdx = (BufferIdx + 1) % NumBytesReadBuffer.Length)
            {
                const int TickInterval = 100;

                long  NumBytesRead      = Interlocked.Read(ref State.NumBytesRead);
                float NumBytesPerSecond = (float)Math.Max(NumBytesRead - NumBytesReadBuffer[BufferIdx], 0) * 1000.0f / (NumBytesReadBuffer.Length * TickInterval);
                NumFilesReportedRead = State.NumFilesRead;
                Log.WriteStatus("Received {0}/{1} files ({2:0.0}/{3:0.0}mb; {4:0.00}mb/s; {5}%)...", NumFilesReportedRead, State.NumFiles, (NumBytesRead / (1024.0 * 1024.0)) + 0.0999999, (NumBytesTotal / (1024.0 * 1024.0)) + 0.0999999, (NumBytesPerSecond / (1024.0 * 1024.0)) + 0.0099, (NumBytesRead * 100) / NumBytesTotal);
                NumBytesReadBuffer[BufferIdx] = NumBytesRead;

                Thread.Sleep(TickInterval);
            }

            // If we finished with an error, try to clean up and return
            if (State.NumFilesRead < State.NumFiles)
            {
                DecompressionThread.Abort();
                foreach (Thread WorkerThread in WorkerThreads)
                {
                    WorkerThread.Abort();
                }
                Log.WriteError("{0}", (State.LastDecompressError != null)? State.LastDecompressError : State.LastDownloadError);
                foreach (string FileName in DownloadFileNames.Values)
                {
                    try { File.Delete(FileName); } catch (Exception) { }
                }
                return(false);
            }

            // Join all the threads
            DecompressionThread.Join();
            foreach (Thread WorkerThread in WorkerThreads)
            {
                WorkerThread.Join();
            }
            Log.FlushStatus();
            return(true);
        }
Beispiel #12
0
        /// <summary>
        /// Handles the Click event of the startRenamingButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void StartRenamingButtonClick(object sender, RoutedEventArgs e)
        {
            if (_renaming)
            {
                if (WorkerThread != null && WorkerThread.IsAlive)
                {
                    try { WorkerThread.Abort(); } catch { }
                }

                startRenamingButton.Content = new StackPanel
                {
                    Orientation = Orientation.Horizontal,
                    Margin      = new Thickness(3, 1, 3, 1)
                };
                (startRenamingButton.Content as StackPanel).Children.Add(new Image
                {
                    Source = new BitmapImage(new Uri("/RSTVShowTracker;component/Images/pencil.png", UriKind.Relative)),
                    Width  = 16,
                    Height = 16,
                    Margin = new Thickness(0, 0, 5, 0),
                });
                (startRenamingButton.Content as StackPanel).Children.Add(new TextBlock
                {
                    Text   = "Start renaming",
                    Margin = new Thickness(0, 0, 3, 0),
                });

                startRenamingButton.IsEnabled = FilesListViewItemCollection.Count(f => f.Enabled && f.Checked) != 0;
                settingsTabItem.IsEnabled     = listView.ContextMenu.IsEnabled = true;
                _parsing = _renaming = false;

                Log.Info("Canceled " + _operationVerb.ToLower() + " operation.");
                SetStatus("Canceled " + _operationVerb.ToLower() + " operation.");
            }
            else
            {
                startRenamingButton.Content = new StackPanel
                {
                    Orientation = Orientation.Horizontal,
                    Margin      = new Thickness(3, 1, 3, 1)
                };
                (startRenamingButton.Content as StackPanel).Children.Add(new Image
                {
                    Source = new BitmapImage(new Uri("/RSTVShowTracker;component/Images/cross.png", UriKind.Relative)),
                    Width  = 16,
                    Height = 16,
                    Margin = new Thickness(0, 0, 5, 0),
                });
                (startRenamingButton.Content as StackPanel).Children.Add(new TextBlock
                {
                    Text   = "Stop renaming",
                    Margin = new Thickness(0, 0, 3, 0),
                });

                settingsTabItem.IsEnabled = listView.ContextMenu.IsEnabled = false;
                _parsing = _renaming = true;

                if (WorkerThread != null && WorkerThread.IsAlive)
                {
                    try { WorkerThread.Abort(); } catch { }
                }

                WorkerThread = new Thread(RenameRecognizedFiles);
                WorkerThread.Start();
            }
        }
Beispiel #13
0
 public void Stop()
 {
     WorkerThread.Abort();
 }