public void TestCancelAsync()
        {
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += DoWorkExpectCancel;
            bw.WorkerSupportsCancellation = true;

            manualResetEvent3 = new ManualResetEventSlim(false);

            bw.RunWorkerAsync("Message");
            bw.CancelAsync();

            bool ret = manualResetEvent3.Wait(TimeoutLong);
            Assert.True(ret);
            // there could be race condition between worker thread cancellation and completion which will set the CancellationPending to false 
            // if it is completed already, we don't check cancellation
            if (bw.IsBusy) // not complete
            {
                if (!bw.CancellationPending)
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        Wait(TimeoutShort);
                        if (bw.CancellationPending)
                        {
                            break;
                        }
                    }
                }
                // Check again
                if (bw.IsBusy)
                    Assert.True(bw.CancellationPending, "Cancellation in Main thread");
            }
        }
 public void CancelAsyncNonBusy()
 {
     var backgroundWorker = new BackgroundWorker<object, object, object>
                 {
                     WorkerSupportsCancellation = true
                 };
     Assert.IsFalse(backgroundWorker.IsBusy);
     backgroundWorker.CancelAsync();
 }
Exemple #3
0
        private void Initialize()
        {
            _bw?.CancelAsync();
            UseWaitCursor     = true;
            _oldSubmoduleInfo = null;
            if (Submodules.SelectedRows.Count == 1)
            {
                _oldSubmoduleInfo = Submodules.SelectedRows[0].DataBoundItem as GitSubmoduleInfo;
            }

            lock (_modules)
            {
                _modules.Clear();
            }

            _bw                            = new BackgroundWorker();
            _bw.DoWork                    += bw_DoWork;
            _bw.ProgressChanged           += bw_ProgressChanged;
            _bw.RunWorkerCompleted        += bw_RunWorkerCompleted;
            _bw.WorkerReportsProgress      = true;
            _bw.WorkerSupportsCancellation = true;
            _bw.RunWorkerAsync();
        }
        public void BackgroundWorker_CancelAsync_ThrowsInvalidOperationExceptionWhenWorkerSupportsCancellationIsFalse()
        {
            using (UnitTestContext context = GetContext())
              {
            BackgroundWorker target = new BackgroundWorker();
            target.DoWork += (o, e) =>
            {
              for (int i = 1; i < 11; i++)
              {
            Thread.Sleep(10);
              }
            };
            target.WorkerSupportsCancellation = false;
            target.RunWorkerAsync(null);

            try
            {
              target.CancelAsync();   // this call throws exception
            }
            catch (InvalidOperationException ex)
            {
              context.Assert.Fail(ex);
            }
            context.Complete();
              }
        }
 public void TestCancelAsyncWithoutCancellationSupport()
 {
     var bw = new BackgroundWorker() { WorkerSupportsCancellation = false };
     Assert.Throws<InvalidOperationException>(() => bw.CancelAsync());
 }
Exemple #6
0
 public void Stop()
 {
     bw.CancelAsync();
 }
Exemple #7
0
 public void Dispose()
 {
     _bw?.CancelAsync();
 }
Exemple #8
0
    private void OnInject(object sender, RoutedEventArgs args)
    {
        if (Context.InjectionMode)
        {
            if (!Utilities.IsRunningAsAdministrator()) // checks whether the app is running as administrator
            {
                MessageBox.Show("Administrative privileges is required in order to inject a DLL into a process!", "Libjector");
                return;
            }
            if (_targetProcessId is null) // checks whether the target process is selected yet
            {
                MessageBox.Show("Select a target process before continuing!", "Libjector");
                return;
            }
            if (DllList.SelectedItem is not DllItemModel dllItem) // checks whether the dll is selected yet
            {
                MessageBox.Show("Select a DLL before continuing!", "Libjector");
                return;
            }
            try
            {
                if (Context.SelectedMethodIndex == 3)
                {
                    var mappingFlags = MappingFlags.None;
                    if (Context.DiscardHeadersFlag)
                    {
                        mappingFlags |= MappingFlags.DiscardHeaders;
                    }
                    if (Context.SkipInitializationRoutinesFlag)
                    {
                        mappingFlags |= MappingFlags.SkipInitialisationRoutines;
                    }
                    _libraryMapper = new LibraryMapper(Process.GetProcessById(_targetProcessId.Value), dllItem.Path, mappingFlags);
                    _libraryMapper.MapLibrary();
                }
                else
                {
                    var injectionFlags = InjectionFlags.None;
                    if (Context.HideDllFlag) // adds hide from peb flag
                    {
                        injectionFlags |= InjectionFlags.HideDllFromPeb;
                    }
                    if (Context.RandomizeHeadersFlag) // adds randomize headers flag
                    {
                        injectionFlags |= InjectionFlags.RandomiseDllHeaders;
                    }
                    if (Context.RandomizeNameFlag) // adds randomize name flag
                    {
                        injectionFlags |= InjectionFlags.RandomiseDllName;
                    }
                    var injectionMethod = Context.SelectedMethodIndex switch
                    {
                        1 => InjectionMethod.HijackThread,
                        2 => InjectionMethod.ManualMap,
                        _ => InjectionMethod.CreateThread
                    };
                    _injectorService?.Dispose();  // disposes any existing injector service
                    _injectorService = new Injector(_targetProcessId.Value, dllItem.Path, injectionMethod, injectionFlags);
                    _injectorService.InjectDll(); // injects dll into the target process
                    if (injectionFlags.HasFlag(InjectionFlags.HideDllFromPeb))
                    {
                        _injectorService.Dispose(); // disposes the injector service; if the specific flag is used
                        goto InjectionCompleted;
                    }
                }
                _processHandler?.Dispose(); // disposes any existing process handler
                _processHandler = new BackgroundWorker {
                    WorkerSupportsCancellation = true
                };
                _processHandler.DoWork += delegate
                {
                    try
                    {
                        using var process = Process.GetProcessById(_targetProcessId.Value);
                        process.WaitForExit(); // waits for the target process to exit
                    }
                    catch
                    {
                        // do nothing
                    }
                };
                _processHandler.RunWorkerCompleted += delegate
                {
                    // disposes any existing services; as the target process has been closed
                    _injectorService?.Dispose();
                    _libraryMapper?.UnmapLibrary();
                    ToggleInjectionMode(true);
                };
                _processHandler.RunWorkerAsync(); // runs until the dll is ejected or the target process is closed
                ToggleInjectionMode(false);
InjectionCompleted:
                MessageBox.Show("The DLL has been injected into the process!", "Libjector");
            }
            catch (Exception exception)
            {
                MessageBox.Show("An error occurred while injecting! " + exception.Message, "Libjector");
            }
        }
        else
        {
            try
            {
                _injectorService?.EjectDll();
                _injectorService?.Dispose();
                _libraryMapper?.UnmapLibrary();
            }
            catch (Exception exception)
            {
                MessageBox.Show("An error occurred while ejecting! " + exception.Message, "Libjector");
            }
            if (_processHandler?.IsBusy == true)
            {
                _processHandler?.CancelAsync(); // cancels the process handler; as the dll has been ejected
            }
            _processHandler?.Dispose();
            ToggleInjectionMode(true);
            MessageBox.Show("The DLL has been ejected from the process!", "Libjector");
        }
    }
Exemple #9
0
 private void SpeedTestForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     autodetector?.Stop();
     bwSpeedTestController?.CancelAsync();
 }
 public void Dispose()
 {
     listenerWorker?.CancelAsync();
     listenWaiter?.Set();
     //listenWaiter.Close();
 }
Exemple #11
0
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            List <AnimeEntry> m_aList = new List <AnimeEntry>();

            double totalProcessedFiles = 0;
            double totalFiles          = int.Parse(new XPathDocument(xmlPath).CreateNavigator().Evaluate("count(//file)").ToString()) * 2;

            using (XmlReader reader = XmlReader.Create(xmlPath))
            {
                reader.ReadToFollowing("mylist");
                if (reader["template"] != "mini")
                {
                    Dispatcher.Invoke(new Action(delegate
                    {
                        MessageBox.Show("Please ensure you selected a mylist export file that used the xml-mini template.",
                                        "Invalid xml template!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }));

                    xmlWorker.CancelAsync();
                    return;
                }


                // <anime>
                while (reader.ReadToFollowing("anime"))
                {
                    while (closePending)
                    {
                        Thread.Sleep(500);
                    }

                    AnimeEntry entry = new AnimeEntry();

                    entry.aid  = int.Parse(reader["aid"]);
                    entry.type = reader["type"];
                    entry.year = reader["year"];

                    // <titles>
                    reader.ReadToFollowing("default");
                    entry.romaji = reader.ReadElementContentAsString();
                    Dispatcher.BeginInvoke(new Action(delegate { importFilePath.Text = String.Format("Reading: {0}", entry.title); }));

                    reader.ReadToFollowing("nihongo");
                    entry.nihongo = reader.ReadElementContentAsString().FormatNullable();

                    reader.ReadToFollowing("english");
                    entry.english = reader.ReadElementContentAsString().FormatNullable();
                    // </titles>

                    // <episodes>
                    if (!reader.ReadToFollowing("episodes"))
                    {
                        goto Finish;
                    }

                    entry.eps_total = int.Parse(reader["total"]);

                    XmlReader episodesReader = reader.ReadSubtree();
                    // <episode>
                    while (episodesReader.ReadToFollowing("episode"))
                    {
                        while (closePending)
                        {
                            Thread.Sleep(500);
                        }

                        EpisodeEntry episode = new EpisodeEntry();

                        episode.eid = int.Parse(episodesReader["eid"]);

                        episode.airdate = episodesReader["aired"] == "-" ? null :
                                          UnixTimestamp.FromDateTime(DateTime.Parse(episodesReader["aired"],
                                                                                    System.Globalization.CultureInfo.CreateSpecificCulture("en-GB")));
                        episode.watched = Convert.ToBoolean(int.Parse(episodesReader["watched"]));

                        if (Regex.IsMatch(episodesReader["epno"].Substring(0, 1), @"\D"))
                        {
                            episode.spl_epno = episodesReader["epno"];
                        }
                        else
                        {
                            episode.epno = int.Parse(episodesReader["epno"]);
                        }

                        // <titles>
                        episodesReader.ReadToDescendant("english");
                        episode.english = episodesReader.ReadElementContentAsString();

                        episodesReader.ReadToFollowing("nihongo");
                        episode.nihongo = episodesReader.ReadElementContentAsString().FormatNullable();

                        episodesReader.ReadToFollowing("romaji");
                        episode.romaji = episodesReader.ReadElementContentAsString().FormatNullable();
                        // </titles>

                        // <files>
                        if (!episodesReader.ReadToFollowing("files"))
                        {
                            goto Finish;
                        }

                        XmlReader filesReader = episodesReader.ReadSubtree();
                        // <file>
                        while (filesReader.ReadToFollowing("file"))
                        {
                            while (closePending)
                            {
                                Thread.Sleep(500);
                            }

                            FileEntry file = new FileEntry();

                            file.fid         = int.Parse(filesReader["fid"]);
                            file.lid         = int.Parse(filesReader["lid"]);
                            file.watcheddate = filesReader["watched"] == "-" ? null :
                                               UnixTimestamp.FromDateTime(DateTime.Parse(episodesReader["watched"],
                                                                                         System.Globalization.CultureInfo.CreateSpecificCulture("en-GB")));
                            file.watched = file.watcheddate != null;
                            file.generic = episodesReader["generic"] != null;

                            if (!file.generic) // generic entries do not have this information
                            {
                                int gid = 0;

                                if (filesReader["gid"] != null)
                                {
                                    gid = int.Parse(filesReader["gid"]);
                                }

                                file.ed2k   = filesReader["ed2k"];
                                file.length = double.Parse(filesReader["length"]);
                                file.size   = double.Parse(filesReader["size"]);
                                file.source = filesReader["source"].FormatNullable();
                                file.acodec = ExtensionMethods.FormatAudioCodec(filesReader["acodec"].FormatNullable());
                                file.vcodec = ExtensionMethods.FormatVideoCodec(filesReader["vcodec"].FormatNullable());
                                file.vres   = filesReader["vres"].FormatNullable();

                                if (gid != 0)
                                {
                                    // <group_name>
                                    filesReader.ReadToFollowing("group_name");
                                    string group_name = filesReader.ReadElementContentAsString();
                                    // </group_name>

                                    // <group_abbr>
                                    filesReader.ReadToFollowing("group_abbr");
                                    string group_abbr = filesReader.ReadElementContentAsString();
                                    // </group_abbr>


                                    file.Group = new GroupEntry
                                    {
                                        gid        = gid,
                                        group_name = group_name,
                                        group_abbr = group_abbr
                                    };
                                }
                            }

                            episode.Files.Add(file);
                            importProgressBar.Dispatcher.BeginInvoke(new Action <double, double>((total, processed) =>
                            {
                                importProgressBar.Value = Math.Ceiling(processed / total * 100);
                            }), totalFiles, ++totalProcessedFiles);
                            // </file>
                        }
                        // </files>
                        filesReader.Close();
                        entry.Episodes.Add(episode);
                        // </episode>
                    }
                    // </episodes>
                    episodesReader.Close();

Finish:
                    m_aList.Add(entry);

                    // </anime>
                }
                // </mylist>
            }

            m_myList.OnEntryInserted += (aTitle) =>
            {
                importProgressBar.Dispatcher.BeginInvoke(new Action(delegate
                {
                    importFilePath.Text     = String.Format("Writing: {0}", aTitle);
                    importProgressBar.Value = Math.Ceiling(++totalProcessedFiles / totalFiles * 100);
                }));
            };

            m_myList.InsertFromImport(m_aList);
        }
 private void buttonCancel_Click(object sender, EventArgs e)
 {
     _backgroundWorker.CancelAsync();
 }
Exemple #13
0
 private void frmExport_FormClosing(object sender, FormClosingEventArgs e)
 {
     _workerJsonLoader.CancelAsync();
     _workerXmlLoader.CancelAsync();
     _workerXmlGenerator.CancelAsync();
 }
 public void StopWork()
 {
     Worker.CancelAsync();
 }
Exemple #15
0
 private void MainWindow_Closed(object sender, EventArgs e)
 {
     worker.CancelAsync();
 }
Exemple #16
0
 private void Timer1OnTick(object sender, EventArgs e)
 {
     DisplayPanelWatch.Text      = DateTime.Now.ToShortTimeString();
     DisplayPanelWatch.ForeColor = Color.Black;
     DisplayPanelWatch.Visible   = true;
     DisplayPanelWatch.Font      = new Font("Segoe UI Symbo", 12F, FontStyle.Regular);
     try
     {
         _server.GetStatus();
         DisplayPanelServerError.Text = string.Empty;
         if (!Trends.Visible)
         {
             DisplayPanelWatch.Visible = true;
             Trends.Visible            = true;
             //Toolbar.Visible = true;
             DisplayPanel.Visible            = Status;
             DisplayPanelServerError.Visible = false;
             _status = true;
         }
         if (_repConnectionWorker.IsBusy)
         {
             _repConnectionWorker.CancelAsync();
         }
     }
     catch (Exception)
     {
         CheckTheConnectionStatus();
         _status = false;
         if (Trends.Visible)
         {
             Trends.Visible = false;
             //Toolbar.Visible = false;
             DisplayPanel.Visible            = Status;
             DisplayPanelServerError.Visible = false;
             DisplayPanelWatch.Visible       = false;
         }
     }
     try
     {
         if (_status)
         {
             //Toolbar.Visible = true;
             Trends.Visible       = true;
             DisplayPanel.Visible = Status;
             OffConnectionDisplayPanelIndicator.Visible  = false;
             OnConnectionDisplayPanelIndicator.Visible   = true;
             OnConnectionDisplayPanelIndicator.ForeColor = Color.Black;
             OnConnectionDisplayPanelIndicator.Font      = new Font("Segoe UI Symbo", 12F, FontStyle.Regular);
             DisplayPanelServerError.Visible             = false;
             DisplayPanelServerError.Text = string.Empty;
         }
         else
         {
             OffConnectionDisplayPanelIndicator.Visible = true;
             DisplayPanelServerError.Visible            = true;
             OnConnectionDisplayPanelIndicator.Visible  = false;
             DisplayPanelServerError.Font            = new Font("Segoe UI Symbo", 12F, FontStyle.Regular);
             OffConnectionDisplayPanelIndicator.Font = new Font("Segoe UI Symbo", 12F, FontStyle.Regular);
             DisplayPanelServerError.Text            = @"|  Ошибка соединения: Идет попытка востановления соединения, пожалуйста подождите";
             DisplayPanel.ForeColor = Color.PaleVioletRed;
             OffConnectionDisplayPanelIndicator.ForeColor = Color.PaleVioletRed;
         }
     }
     catch (Exception)
     {
     }
 }
Exemple #17
0
 public void CancelGame()
 {
     worker.CancelAsync();
 }
 private void stopButton_Click(object sender, EventArgs e)
 {
     _controller.SetCancelFlag(true);
     _getImagesWorker?.CancelAsync();
     SetImageCountText();
 }
Exemple #19
0
 internal void Cancel()
 {
     Worker.CancelAsync();
     Client.CancelAsync();
 }
 protected void CancelAsync()
 {
     _worker?.CancelAsync();
 }
Exemple #21
0
        private void button1_Click(object sender, EventArgs e)
        {
            _worker = new BackgroundWorker();
            _worker.WorkerSupportsCancellation = true;

            _worker.DoWork += new DoWorkEventHandler((state, args) =>
            {
                int i = 0;

                do
                {
                    if (_worker.CancellationPending)
                    {
                        break;
                    }

                    switch (Pi[i])
                    {
                    case '1':
                        Player("Sounds/a1.wav");
                        break;

                    case '2':
                        Player("Sounds/a1s.wav");
                        break;

                    case '3':
                        Player("Sounds/b1.wav");
                        break;

                    case '4':
                        Player("Sounds/c1.wav");
                        break;

                    case '5':
                        Player("Sounds/c1s.wav");
                        break;

                    case '6':
                        Player("Sounds/c2.wav");
                        break;

                    case '7':
                        Player("Sounds/d1.wav");
                        break;

                    case '8':
                        Player("Sounds/e1.wav");
                        break;

                    case '9':
                        Player("Sounds/f1.wav");
                        break;

                    case '0':
                        Player("Sounds/g1.wav");
                        break;

                    default:
                        break;
                    }

                    i++;
                } while (true);
            });

            if (button1.Text == "Start")
            {
                _worker.RunWorkerAsync();
                button1.Text = "Stop";
            }
            else
            {
                _worker.CancelAsync();
                button1.Text = "Start";
            }
        }
Exemple #22
0
 private void OnlineBackupLogin_FormClosing(object sender, FormClosingEventArgs e)
 {
     bw?.CancelAsync();
 }
 private void _cancelButton_Click(object sender, RoutedEventArgs e)
 {
     _worker.CancelAsync();
 }
Exemple #24
0
 private void OnUnloaded(object sender, RoutedEventArgs e)
 {
     _backgroundWorker?.CancelAsync();
 }
Exemple #25
0
 private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
 {
     _backgroundWorker?.CancelAsync();
 }
Exemple #26
0
 public void Dispose()
 {
     _bw?.CancelAsync();
     _bw = null;
 }
Exemple #27
0
 public void CancelSearch()
 {
     _worker?.CancelAsync();
 }
        public void TestCancelInsideDoWork()
        {
            var original = SynchronizationContext.Current;
            try
            {
                SynchronizationContext.SetSynchronizationContext(null);

                var bw = new BackgroundWorker() { WorkerSupportsCancellation = true };
                var barrier = new Barrier(2);

                bw.DoWork += (sender, e) =>
                {
                    barrier.SignalAndWait();
                    barrier.SignalAndWait();

                    if (bw.CancellationPending)
                    {
                        e.Cancel = true;
                    }
                };

                bw.RunWorkerCompleted += (sender, e) =>
                {
                    Assert.True(e.Cancelled);
                    barrier.SignalAndWait();
                };

                bw.RunWorkerAsync();
                barrier.SignalAndWait();
                bw.CancelAsync();
                barrier.SignalAndWait();
                Assert.True(barrier.SignalAndWait(TimeoutLong), "Background work timeout");
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(original);
            }
        }
Exemple #29
0
 public void Close()
 {
     _eternalQueueListener?.CancelAsync();
     _queueReader?.CancelAsync();
 }
Exemple #30
0
 private void WindowClosing()
 {
     DisableElements();
     _backgroundWorker?.CancelAsync();
     EnableElements();
 }
        public void BackgroundWorker_CancelAsync_ReportsCancelledWhenWorkerSupportsCancellationIsTrue()
        {
            UnitTestContext context = GetContext();

              int numTimesProgressCalled = 0;

              BackgroundWorker target = new BackgroundWorker();
              target.DoWork += (o, e) =>
              {
            // report progress changed 10 times
            for (int i = 1; i < 11; i++)
            {
              Thread.Sleep(100);
              if (target.CancellationPending)
              {
            e.Cancel = true;
            return;
              }
            }
              };
              target.WorkerSupportsCancellation = true;
              target.RunWorkerCompleted += (o, e) =>
              {
            //  target does not support ReportProgress we shold get a System.InvalidOperationException from DoWork
            context.Assert.IsNull(e.Error);
            context.Assert.IsTrue(e.Cancelled);
            context.Assert.Success();
              };
              target.RunWorkerAsync(null);
              target.CancelAsync();
              context.Complete();
        }
        public bool Stop()
        {
            if (_stopped)
            {
                return(_stopped);
            }

            _started = false;
            _stopped = true;

            try
            {
                if (_worker.WorkerSupportsCancellation)
                {
                    _worker?.CancelAsync();
                }
            }
            catch
            {
                // ignore
            }

            // in case any train is running
            // let them reach their destination
            var tasks = GetRunningRouteThreads();

            if (tasks.Count > 0)
            {
                DoWorkWithModal(progress =>
                {
                    for (;;)
                    {
                        var ts = GetRunningRouteThreads();
                        if (ts.Count == 0)
                        {
                            break;
                        }

                        int n = ts.Count;
                        if (n > 1)
                        {
                            progress.Report($"Wait for {ts.Count} trains which run for reaching their destination.");
                        }
                        else
                        {
                            progress.Report($"Wait for one train until it reaches its final destination.");
                        }

                        System.Threading.Thread.Sleep(250);
                    }
                });
            }

            try
            {
                StopRouteThreads();
            }
            catch
            {
                // ignore
            }

            if (Stopped != null)
            {
                Stopped(this, null);
            }

            return(true);
        }
 public void StopServiceAsync()
 {
     _cameraWorker?.CancelAsync();
 }
 private void btnCancel_Click(object sender, EventArgs e)
 {
     importWorker?.CancelAsync();
 }
 public override void Stop()
 {
     _backgroundWorkerCleaning?.CancelAsync();
 }
Exemple #36
0
 /// <summary>
 /// Stop Indeterminate Progress Bar Animation.
 /// </summary>
 public void DoEnd()
 {
     IsRunning = false;
     _bgTask?.CancelAsync();
     _bgTask = null;
 }
 public void CancelAsyncNoCancellationSupported()
 {
     var backgroundWorker = new BackgroundWorker<object, object, object>();
     Assert.IsFalse(backgroundWorker.IsBusy);
     backgroundWorker.CancelAsync();
 }