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

Windows Forms Discussion :

Problème avec BackgroundWorker


Sujet :

Windows Forms

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Nouveau candidat au Club
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    2
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 2
    Par défaut Problème avec BackgroundWorker
    Bonjour à tous.

    Je code en C# depuis qq semaines seulement et je suis en train de galérer avec les Threads. J'ai lu un peu partout que le composant BackgroundWorker correspondait bien à mes besoins. Seulement il y a un problème : lorsque le calcul en tache de fond est lancé, impossible de clicker sur le boutton annuler qui semble complètement figé. J'ai suivi le tuto http://glarde.developpez.com/dotnet/bgworker/cs/
    Je ne vois pas quelle erreur j'ai pu commettre ou ce que j'ai oublié.
    Merci de votre aide.

    LoadingForm.cs :
    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
    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
     
    /* Default */
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    /* System */
    using System.IO;
     
    namespace NewTestProject
    {
        public partial class LoadingForm : Form
        {
            private string Filename;
     
            public LoadingForm(string filename)
            {
                InitializeComponent();
                this.Filename = filename;
            }
     
            private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                e.Result = this.LoadFromFile(worker, e);
            }
     
            private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                this.progressBar1.Value = e.ProgressPercentage;
            }
     
            private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    MessageBox.Show(e.Error.Message);
                    this.DialogResult = DialogResult.Abort;
                }
                else if (e.Cancelled)
                {
                    this.DialogResult = DialogResult.Cancel;
                }
                else
                {
                    this.DialogResult = DialogResult.OK;
                }
            }
     
            private void cancelButton_Click(object sender, EventArgs e)
            {
                this.backgroundWorker1.CancelAsync();
                this.cancelButton.Enabled = false;
            }
     
            private void LoadingForm_Load(object sender, EventArgs e)
            {
                this.progressBar1.Value = 0;
                //this.backgroundWorker1.RunWorkerAsync();
            }
     
            private bool LoadFromFile(BackgroundWorker worker, DoWorkEventArgs e)
            {
                for (int i = 0; i < 100; i++)
                {
                    if (i == 99)
                        i = 0;
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return false;
                    }
                    else
                        worker.ReportProgress(i);
                }
     
                return false;
            }
     
            private void startButton_Click(object sender, EventArgs e)
            {
                this.backgroundWorker1.RunWorkerAsync();
            }
        }
    }
    LoadingForm.Designer.cs :
    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
    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
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
     
    namespace NewTestProject
    {
        partial class LoadingForm
        {
            /// <summary>
            /// Variable nécessaire au concepteur.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
     
            /// <summary>
            /// Nettoyage des ressources utilisées.
            /// </summary>
            /// <param name="disposing">true si les ressources managées doivent être supprimées ; sinon, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
     
            #region Code généré par le Concepteur Windows Form
     
            /// <summary>
            /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
            /// le contenu de cette méthode avec l'éditeur de code.
            /// </summary>
            private void InitializeComponent()
            {
                this.progressBar1 = new System.Windows.Forms.ProgressBar();
                this.cancelButton = new System.Windows.Forms.Button();
                this.label1 = new System.Windows.Forms.Label();
                this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
                this.startButton = new System.Windows.Forms.Button();
                this.SuspendLayout();
                // 
                // progressBar1
                // 
                this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                            | System.Windows.Forms.AnchorStyles.Left)
                            | System.Windows.Forms.AnchorStyles.Right)));
                this.progressBar1.Location = new System.Drawing.Point(45, 30);
                this.progressBar1.Name = "progressBar1";
                this.progressBar1.Size = new System.Drawing.Size(197, 19);
                this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
                this.progressBar1.TabIndex = 0;
                // 
                // cancelButton
                // 
                this.cancelButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
                this.cancelButton.Location = new System.Drawing.Point(104, 74);
                this.cancelButton.Name = "cancelButton";
                this.cancelButton.Size = new System.Drawing.Size(75, 23);
                this.cancelButton.TabIndex = 1;
                this.cancelButton.Text = "Cancel";
                this.cancelButton.UseVisualStyleBackColor = true;
                this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
                // 
                // label1
                // 
                this.label1.AutoSize = true;
                this.label1.Location = new System.Drawing.Point(42, 14);
                this.label1.Name = "label1";
                this.label1.Size = new System.Drawing.Size(35, 13);
                this.label1.TabIndex = 2;
                this.label1.Text = "label1";
                // 
                // backgroundWorker1
                // 
                this.backgroundWorker1.WorkerReportsProgress = true;
                this.backgroundWorker1.WorkerSupportsCancellation = true;
                this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
                this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
                this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
                // 
                // startButton
                // 
                this.startButton.Location = new System.Drawing.Point(23, 74);
                this.startButton.Name = "startButton";
                this.startButton.Size = new System.Drawing.Size(75, 23);
                this.startButton.TabIndex = 3;
                this.startButton.Text = "Start";
                this.startButton.UseVisualStyleBackColor = true;
                this.startButton.Click += new System.EventHandler(this.startButton_Click);
                // 
                // LoadingForm
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(292, 109);
                this.Controls.Add(this.startButton);
                this.Controls.Add(this.label1);
                this.Controls.Add(this.cancelButton);
                this.Controls.Add(this.progressBar1);
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
                this.MaximizeBox = false;
                this.MinimizeBox = false;
                this.Name = "LoadingForm";
                this.ShowIcon = false;
                this.Text = "Loading";
                this.TopMost = true;
                this.Load += new System.EventHandler(this.LoadingForm_Load);
                this.ResumeLayout(false);
                this.PerformLayout();
     
            }
     
            #endregion
     
            private System.Windows.Forms.Button cancelButton;
            public System.Windows.Forms.ProgressBar progressBar1;
            public System.Windows.Forms.Label label1;
            private System.ComponentModel.BackgroundWorker backgroundWorker1;
            private System.Windows.Forms.Button startButton;
        }
    }

  2. #2
    Expert confirmé

    Homme Profil pro
    Chef de projet NTIC
    Inscrit en
    Septembre 2006
    Messages
    3 580
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Chef de projet NTIC
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Septembre 2006
    Messages : 3 580
    Par défaut
    salut

    je glisserais un tout petit :

    Application.DoEvents() ou bien un Thread.Sleep(0) dans ta boucle for(i)
    qui se trouve dans la methode LoadFromFile()

    Car la, ton backgroundWorkerThread monopolise toute la CPU pour lui
    le coquin

    The Monz, Toulouse

  3. #3
    Nouveau candidat au Club
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    2
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 2
    Par défaut
    Le "Application.DoEvents()" ne fait pas beaucoup d'effet. En revanche le "Thread.Sleep(0)" fonctionne mais ne me semble pas très élégant. J'ai simplifié dans cet exemple la fonction LoadFromFile qui est en réalité beaucoup plus complexe. S'il faut que j'insère des "Sleep(0)" un peu partout ça va vite devenir indigeste.

    L'intérêt d'un thread n'est il pas de répartir les ressources CPU entre plusieurs calculs ? Pourquoi diable le BackgroundWorker monopoliserait tout pour lui tout seul ?

    Enfin cette solution a le mérite de fonctionner. Merci.

Discussions similaires

  1. Backgroundworker problème avec l’évènement Progresschanged
    Par Aeronia dans le forum Windows Forms
    Réponses: 3
    Dernier message: 10/11/2011, 08h40
  2. Réponses: 4
    Dernier message: 16/10/2008, 09h48
  3. [C# THREADS]problème avec backgroundworker
    Par sarapis dans le forum Windows Forms
    Réponses: 8
    Dernier message: 15/04/2007, 11h58
  4. Problème avec la mémoire virtuelle
    Par Anonymous dans le forum CORBA
    Réponses: 13
    Dernier message: 16/04/2002, 16h10

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