IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

VB.NET Discussion :

Stopper le backgroundworker


Sujet :

VB.NET

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre émérite

    Homme Profil pro
    Inscrit en
    Mars 2012
    Messages
    691
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Israël

    Informations forums :
    Inscription : Mars 2012
    Messages : 691
    Par défaut Stopper le backgroundworker
    Bonjour,

    J'esssaie de stopper le backgroundworker


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
     Private Sub ToolStripButtonNew_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ToolStripButtonNew.MouseDown
          backgroundWorker1.WorkerSupportsCancellation = True
            backgroundWorker1.CancelAsync()
        End Sub
     
     
     Private Sub Buttonvalid_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Buttonvalid.MouseClick
     backgroundWorker1.RunWorkerAsync()
    end sub
     
    Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles backgroundWorker1.DoWork
     
     If backgroundWorker1.CancellationPending Then
                e.Cancel = True
            End If
    'do something 
    end sub
    le résultat si je clique sur le toolStripButtonNew et ensuite sur le boutonvalid
    une exception à backgroundWorker1.RunWorkerAsync()
    backgroundWorker1 n'est pas libre

    merci

  2. #2
    Membre Expert
    Avatar de wallace1
    Homme Profil pro
    Administrateur systèmes
    Inscrit en
    Octobre 2008
    Messages
    1 966
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : Administrateur systèmes
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Octobre 2008
    Messages : 1 966
    Billets dans le blog
    7
    Par défaut
    Bonjour shayw,

    Avant de lancer la méthode "RunWorkerAsync" il faut s'assurer que le BGW ne soit pas déjà en cours d'exécution comme ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    If not backgroundWorker1.isBusy
        backgroundWorker1.RunWorkerAsync()
    End if
    Cela devrait résoudre ton problème.


    A+

  3. #3
    Membre Expert Avatar de callo
    Homme Profil pro
    Administrateur systèmes et réseaux
    Inscrit en
    Février 2004
    Messages
    887
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Togo

    Informations professionnelles :
    Activité : Administrateur systèmes et réseaux
    Secteur : Service public

    Informations forums :
    Inscription : Février 2004
    Messages : 887
    Par défaut
    Bonjour shayw,

    Je ne sais pas quel impact
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     backgroundWorker1.WorkerSupportsCancellation = True
    aura sur le fonctionnnement de ton code dans l'event ToolStripButtonNew_MouseDown, mais je crois qu'il serait plus pratique de mettre ce code dans l'initialisation de ton bgw; ainsi il ne sera appelé qu'une seule fois.
    Maintenant, voici comment moi je procède pour arrêter le bgw:
    Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    private void BtnCancel_Click(object sender, EventArgs e)
    {
        // Notify the worker thread that a cancel has been requested.
        // The cancel will not actually happen until the thread in the
        // DoWork checks the BgWorker.CancellationPending flag. 
        if (_bgWorker.IsBusy)
        {
           _bgWorkerCust.CancelAsync();
        }
    }
    Désolé, c'est du c#. Essayes de jouer sur la propriété IsBusy du bgw; cela devrait résoudre ton problème.
    [Edit]grillé par wallace [/Edit]

  4. #4
    Membre émérite

    Homme Profil pro
    Inscrit en
    Mars 2012
    Messages
    691
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Israël

    Informations forums :
    Inscription : Mars 2012
    Messages : 691
    Par défaut
    Bonjour

    Je n'ai pas réussi
    J'ai bien ajouté la condition
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    If not backgroundWorker1.isBusy
            backgroundWorker1.RunWorkerAsync()
       End if
    et dans le ToolStripButtonNew_MouseDown
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    If backgroundWorker1.IsBusy Then
                backgroundWorker1.CancelAsync()
            End If
    Pour mieux comprendre j'ai un bouton nouveau et un bouton valid
    le clique sur nouveau doit stopper le bgw
    le bouton valid est enable seulement si des données ont été introduit
    et le clique active le bgw

    ce que j'essaie possible que j'ai mal expliqué après avoir stopper le bgw
    la possibllité de le réutiliser

    pour tester

    J'ai placé un breakpoint à la ligne If backgroundWorker1.IsBusy
    Je lance le prog si je clique sur ToolStripButtonNew_MouseDown
    le watch indique backgroundWorker1.IsBusy = false
    ensuite je clique sur le bouton valid qui appelle le backgroundWorker1.RunWorkerAsync()
    maintenant je clique sur ToolStripButtonNew
    le watch indique backgroundWorker1.IsBusy = true
    je continue pas à pas
    backgroundWorker1.CancelAsync()
    je verifie ensuite le backgroundWorker1.IsBusy
    bizarre c'est toujours à true

  5. #5
    Rédacteur/Modérateur


    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    19 875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2004
    Messages : 19 875
    Par défaut
    Le BackgroundWorker ne peut pas s'arrêter tout seul ; c'est à toi, dans le code de l'évènement DoWork, de vérifier régulièrement si CancellationPending vaut true, et d'arrêter ton traitement si c'est le cas.

  6. #6
    Membre Expert Avatar de callo
    Homme Profil pro
    Administrateur systèmes et réseaux
    Inscrit en
    Février 2004
    Messages
    887
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Togo

    Informations professionnelles :
    Activité : Administrateur systèmes et réseaux
    Secteur : Service public

    Informations forums :
    Inscription : Février 2004
    Messages : 887
    Par défaut
    En général j'ai la structure suivante pour mes bgw et ça fonctionne bien; essayes de voir si tu peux en tirer quelque chose:
    Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    BackgroundWorker _bgWorkerCust;
     
    public FrmSearchCustomer()
    {
    	InitializeComponent();
    	_bgWorkerCust = new BackgroundWorker();
    	InitBgw();
    }
     
    private void InitBgw()
    {
    	_bgWorkerCust.DoWork += BgWorkerCust_DoWork;
    	_bgWorkerCust.ProgressChanged += BgWorkerCust_ProgressChanged;
    	_bgWorkerCust.RunWorkerCompleted += BgWorkerCust_RunWorkerCompleted; 
    	_bgWorkerCust.WorkerReportsProgress = true;
    	_bgWorkerCust.WorkerSupportsCancellation = true;
    }
     
    private void BtnDemarrerBgw_Click(object sender, EventArgs e)
    {
    	// ...
    	LaunchLongProcess();
    }
     
    private void LaunchLongProcess()
    {
    	BtnDemarrerBgw.Enabled = false;
    	BtnCancel.Enabled = true;
    	string keyword = SearchTextBox.Text.Trim();
    	_bgWorkerCust.RunWorkerAsync(keyword); 
    }
     
    private void BgWorkerCust_DoWork(object sender, DoWorkEventArgs e)
    {
    	string arg = (string)e.Argument;
     
    	_bgWorkerCust.ReportProgress(...); 
    	//  ....
    	_list = BLLClients.GetCustomerByName(arg); // the lengthy operation 
     
    	//If cancel button was pressed while the execution is in progress
    	//Change the state from cancellation ---> cancel'ed
    	if (_bgWorkerCust.CancellationPending)
    	{
    		e.Cancel = true;
    		//...
    		return;
    	}
    }
     
    private void BgWorkerCust_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    	LoadingLabel.Visible = true;
    	LoadingPictureBox.Visible = true;
    }
     
    private void BgWorkerCust_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    	LoadingLabel.Visible = false;
    	LoadingPictureBox.Visible = false;
     
    	BtnDemarrerBgw.Enabled = true;
    	BtnCancel.Enabled = false;
     
    	if (e.Cancelled)
    	{
    		MessageBox.Show("Opération de recherche annulée par l'utilisateur!");
    	}
     
    	else if (e.Error != null)
    	{
    		MessageBox.Show("Une erreur s'est produite au cours de la recherche :\n\r" + e.Error.Message);
    	}
     
    	else // opération de effectuée avec succès
    	{
    		customerListBindingSource.DataSource = new SortableBindingList<CustomerList>(_list);
    	    // ...
    	}
    }
     
    private void BtnCancel_Click(object sender, EventArgs e)
    {
    	// Notify the worker thread that a cancel has been requested.
    	// The cancel will not actually happen until the thread in the
    	// DoWork checks the BgWorkerCust.CancellationPending flag. 
    	if (_bgWorkerCust.IsBusy)
    	{
    		_bgWorkerCust.CancelAsync();
            }
    }

  7. #7
    Membre Expert
    Avatar de wallace1
    Homme Profil pro
    Administrateur systèmes
    Inscrit en
    Octobre 2008
    Messages
    1 966
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : Administrateur systèmes
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Octobre 2008
    Messages : 1 966
    Billets dans le blog
    7
    Par défaut
    J'avais posté sur le forum un projet exemple qui visait à lire un gros fichier tout en affichant une barre de progression à l'aide du BackgroundWorker.
    Ce projet permettait aussi d'annuler l'opération.
    Le bouton sert à lancer et à annuler la tache.

    Voilà le projet :

    http://wallace87000.upd.fr/ReadBigFile.zip

    PS : N'oublies pas de remplacer la valeur de la variable nommée "_BigFilePath" par le chemin d'un fichier d'une assez grande capacité !


    EDIT : voilà le sujet : http://www.developpez.net/forums/d13...r/#post7569916


    A+

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Stopper plein de processus
    Par tomsoyer dans le forum Linux
    Réponses: 1
    Dernier message: 30/11/2004, 19h16
  2. Réponses: 17
    Dernier message: 19/10/2004, 09h05
  3. Stopper le port d'écoute 8081
    Par vbcasimir dans le forum Réseau
    Réponses: 2
    Dernier message: 28/09/2004, 13h37
  4. [NVidia] Démarrer ou stopper sortie Tv
    Par nico-21 dans le forum DirectX
    Réponses: 2
    Dernier message: 31/05/2004, 11h59
  5. Stopper la répétition du clavier
    Par Chris89 dans le forum Assembleur
    Réponses: 6
    Dernier message: 17/10/2003, 20h53

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo