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 :

Thread, delegate, join, process et progress bar


Sujet :

Windows Forms

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Inscrit en
    Février 2011
    Messages
    21
    Détails du profil
    Informations forums :
    Inscription : Février 2011
    Messages : 21
    Par défaut Thread, delegate, join, process et progress bar
    Bonjour à tous,

    Je souhaite, grâce à mon programme en C# winform, effectuer deux actions:

    1) transformer des .log en .txt
    2) les insérer dans une BDD

    • Pour l'étape 1) je possède un logiciel qui s'occupe de çà, je fais donc un process.start de l'outil. Je souhaiterais également avoir une progressbar en indeterminate (bar qui fait des aller-retour)
    • L'etape 2) ne doit commencer qu'une fois l'etape 1) terminée. Une fois que l'étape 2) commence la progressbar doit alors se transformer en une "continue" ou l'insertion ligne par ligne dans ma BDD fait progresser la progressbar


    Le souci c'est qu'apres avoir essayer toute sorte de thread, delegate, process waitForExit, HasExited, je crois bien que je me suis emmêler dans tout ca.

    J'aimerai donc savoir quel est la meilleure solution pour faire l'etape 1 puis 2 avec cette progressbar qui fonctionne.


    PS: A savoir que pour l'instant mon code fonctionne, mais le clic sur le bouton qui permet de lancer tout ça ne peut être fait qu'une seule fois.. En effet lorsque je re-clic après une première insertion dans ma BDD, toute mon application freeze.
    Pourquoi je cherche pas a changer ce qui empeche de recommencer?
    Car lorsque je debug en pas à pas j'ai le problème suivant :
    Opération inter-threads non valide*: le contrôle 'progressBar1' a fait l'objet d'un accès à partir d'un thread autre que celui sur lequel il a été créé.

    Je souhaiterais donc repartir du début et avoir quelque chose de propre.
    A moins que ceci soit correct... :

    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
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            private System.Diagnostics.Process proc;
            int inbline = 0;
            char[] delimiterChars = { '|' };
            char[] delimiterCharstiret = { '-' };
            int counter = 0;
            string l = "";
            string line = "";
            int pgval = 0;
     
            private void myProcess_Exited(object sender, System.EventArgs e)
            {
                //proc.Dispose();
     
                if (checkBoxEngineering.Checked == true)
                {   
                    getLogIntoDB("Engineering");
                }
                if (checkBoxClient.Checked == true)
                {   
                    getLogIntoDB("Client");
                }
                if (checkBoxWatchdog.Checked == true)
                {   
                    getLogIntoDB("Watchdog");
                }
     
            }
     
            void UpdateProgressSafe(int value)
            {
                if (inbline != 0)
                { 
                    pgval = (value * 100) / inbline; 
                }
                else 
                { 
                    pgval = 0; 
                }
                this.progressBar1.Value = pgval;
            }
     
            delegate void UpdateProgressDelegate(int value);
            //delegate void progressbarVisuDelegate(int ivStep);
     
            public Form1()
            {
                InitializeComponent();
            }
     
            private void progressbarVisu(int step)
            {
                if (step == 1)
                {
                    progressBar1.Visible = true;
                    labelpgb.Text = "Conversion from Log file to text file ..";
                    labelpgb.Visible = true;
                }
                if (step == 2)
                {
                    progressBar1.Style = ProgressBarStyle.Marquee;
                    progressBar1.MarqueeAnimationSpeed = (40);
                }
                if (step == 3)
                {
                    progressBar1.MarqueeAnimationSpeed = 0;
                    progressBar1.Style = ProgressBarStyle.Continuous;
                }
                if (step == 4)
                {
                    progressBar1.Maximum = 190;
                    progressBar1.Value = 0;
                    labelpgb.Text = "Sending data to MySQL server ..";
                }
                if (step == 5)
                {
                    labelpgb.Visible = false;
                    progressBar1.Value = 0;
                    progressBar1.Visible = false;
                }
            }
     
            private void beginAlogToDB(string folderPath)
            {
                //progressbarVisuDelegate pgb = new progressbarVisuDelegate(progressbarVisu);
                progressbarVisu(2);
     
                string exeDir = Application.StartupPath;
     
                System.Diagnostics.ProcessStartInfo p = new System.Diagnostics.ProcessStartInfo("ALogToTxtTool.exe");
                p.Arguments = @"/k --infolder=" + folderPath + " --outfolder=" + exeDir + " " + txtClient + " " + txtEngineering + " " + txtWatchdog;
                p.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                proc = new System.Diagnostics.Process();
                proc.StartInfo = p;
                proc.EnableRaisingEvents = true;
                proc.Exited += new EventHandler(myProcess_Exited);
                proc.Start();
            }
     
            public void sendToClient(string[] files, string fichier, MySqlConnection connection, MySqlCommand command)
            {   
                // The delegate member
                UpdateProgressDelegate UpdateProgress = new UpdateProgressDelegate(UpdateProgressSafe);
     
                if (fichier.Substring(fichier.Length - 9) == ".ALog.txt" && (fichier.IndexOf("Client") != -1 || fichier.IndexOf("client") != -1))
                {
                    StreamReader file = new StreamReader(fichier, System.Text.Encoding.Default);
                    connection.Open();
                    while ((line = file.ReadLine()) != null)
                    {
                        if ((counter > 4) && (CountStringOccurrences(line, "|") == 9))
                        {
                            line = line.Replace("'", "_");
                            string[] words = line.Split(delimiterChars);
                            string[] dateandtime = words[0].Split(delimiterCharstiret);
                            command.CommandText = "INSERT INTO logs_client VALUES ('" + dateandtime[0] + "', '" + dateandtime[1] + "', '" + words[1] + "', '" + words[2] + "', '" + words[3] + "', '" + words[4] + "', '" + words[5] + "', '" + words[6] + "', '" + words[7] + "', '" + words[8] + "' )";
                            command.ExecuteNonQuery();
     
                            progressBar1.Invoke(UpdateProgress, counter);
                        }
                        else if (counter > 4)
                        {
                            MessageBox.Show("Insert line error");
                        }
                        counter++;
                    }
                    connection.Close();
                    MessageBox.Show("You have been successfully insert logs into logs_client database");
                    counter = 0;
                }  
            }
     
            public void sendToEngineering(string[] files, string fichier, MySqlConnection connection, MySqlCommand command)
            {
                // The delegate member
                UpdateProgressDelegate UpdateProgress = new UpdateProgressDelegate(UpdateProgressSafe);
     
                if (fichier.Substring(fichier.Length - 9) == ".ALog.txt" && (fichier.IndexOf("Engineering") != -1 || fichier.IndexOf("engineering") != -1))
                {
                    // Read the file and display it line by line.
                    StreamReader file = new StreamReader(fichier, System.Text.Encoding.Default);
                    connection.Open();
                    while ((line = file.ReadLine()) != null)
                    {
                        if ((counter > 4) && (CountStringOccurrences(line, "|") == 6))
                        {
                            line = line.Replace("'", "_");
                            string[] words = line.Split(delimiterChars);
                            string[] dateandtime = words[0].Split(delimiterCharstiret);
                            command.CommandText = "INSERT INTO logs_engineering VALUES ('" + dateandtime[0] + "', '" + dateandtime[1] + "', '" + words[1] + "', '" + words[2] + "', '" + words[3] + "', '" + words[4] + "', '" + words[5] + "' )";
                            command.ExecuteNonQuery();
     
                            progressBar1.Invoke(UpdateProgress, counter);
                        }
                        else if (counter > 4)
                        {
                            MessageBox.Show("Insert line error");
                        }
                        counter++;
                     }
                     connection.Close();
                     MessageBox.Show("You have been successfully insert logs into logs_engineering database");
                     counter = 0;
                  }
            }
     
            public void getLogIntoDB(string type)
            {
                string MyConString = "SERVER=localhost;" +
                            "DATABASE=logs;" +
                            "UID=root;" +
                            "PASSWORD=root;";
     
                MySqlConnection connection = new MySqlConnection(MyConString);
                MySqlCommand command = connection.CreateCommand();
     
                string exeDir = Application.StartupPath;
                String[] files = Directory.GetFiles(exeDir);
     
                foreach (string fichier in files)
                {
                    StreamReader lefile = new StreamReader(fichier, System.Text.Encoding.Default);
                    connection.Open();
                    while ((l = lefile.ReadLine()) != null)
                    {
                        l = lefile.ReadLine();
                        if (l == null) { break; }
                        else { inbline++; }
                    }
                    connection.Close();
                    if (fichier.Length > 9)
                    {
                        progressbarVisu(3);
                        progressbarVisu(4);
     
                        if (type == "Client")
                        {
                            sendToClient(files, fichier, connection, command);
                        }
     
                        if (type == "Engineering")
                        {
                            sendToEngineering(files, fichier, connection, command);
                        }
     
                    }
                }
                inbline = 0;
                progressbarVisu(5);
            }
     
     private void buttonGet_Click(object sender, EventArgs e)
            {
                listBox1.Items.Clear();
                folderBrowserDialog1.ShowDialog();
                string folderPath = folderBrowserDialog1.SelectedPath;
                if (folderPath != "")
                {
                    progressbarVisu(1);
                    beginAlogToDB(folderPath);
                }
                else
                { 
                    MessageBox.Show("Please select a correct folder path"); 
                }
            }
    Merci d'avance pour votre aide!

  2. #2
    Membre averti
    Inscrit en
    Février 2011
    Messages
    21
    Détails du profil
    Informations forums :
    Inscription : Février 2011
    Messages : 21
    Par défaut
    Pour préciser rapidement ce que fais le code que j'ai posté:

    Dans un premier temps il lance la fonction : beginAlogToDB qui s'occupe de lancer le processus qui transforme les log en fichier .txt.
    Ce processus est couplé d'un:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    proc.Exited += new EventHandler(myProcess_Exited);
    qui lui permet de ne pas freezer comme l'aurait fait un WaitForExit. De plus j'affiche la progressbar1 en indeterminate.

    Une fois le processus terminé la fonction myProcess_Exited est exécutée ou la fonction getLogIntoDB("Client");,getLogIntoDB("Engineering");.. est à son tour exécutée. Dans ces fonctions j'utilise :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    progressBar1.Invoke(UpdateProgress, counter);
    qui vient mettre a jour la progressbar1 avec un delegate et la fonction UpdateProgressSafe :

    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
            void UpdateProgressSafe(int value)
            {
                if (inbline != 0)
                { 
                    pgval = (value * 100) / inbline; 
                }
                else 
                { 
                    pgval = 0; 
                }
                this.progressBar1.Value = pgval;
            }
     
            delegate void UpdateProgressDelegate(int value);
            //delegate void progressbarVisuDelegate(int ivStep);

  3. #3
    Membre averti
    Inscrit en
    Février 2011
    Messages
    21
    Détails du profil
    Informations forums :
    Inscription : Février 2011
    Messages : 21
    Par défaut

  4. #4
    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
    Citation Envoyé par LsMarx Voir le message
    Bonjour à tous,

    Car lorsque je debug en pas à pas j'ai le problème suivant :
    Opération inter-threads non valide*: le contrôle 'progressBar1' a fait l'objet d'un accès à partir d'un thread autre que celui sur lequel il a été créé.

    Merci d'avance pour votre aide!
    Tu essayes d'accéder à un élément d'une form à partir d'un thread autre celui qui a crée cet élément; C'est la raison de cette erreur. En fait, avec C#, tu ne peux accéder aux éléments d'un formulaire qu'à partir du thread qui les as créés.

    Il est tout de même possible de mettre à jour ton IHM en passant par la méthode Invoke. Pour celà, regarde cet article.

    As-tu tout de même essayer de passer par le composant BackGroundWorker ?

  5. #5
    Membre averti
    Inscrit en
    Février 2011
    Messages
    21
    Détails du profil
    Informations forums :
    Inscription : Février 2011
    Messages : 21
    Par défaut
    Merci Callo pour ton aide.
    Je suis finalement passé par la méthode invoke en appelant directement mes "form" depuis le thread principal, comme ceci:

    this.Invoke((MethodInvoker)delegate { progressBar3.Hide(); }); // runs on UI thread


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

Discussions similaires

  1. [Débutant] Progress bar dans un nouveau thread ?
    Par yayou49 dans le forum VB.NET
    Réponses: 6
    Dernier message: 30/03/2015, 11h45
  2. [Débutant] BackgroundWorker, Progress Bar et utilisation de Thread multiples ?
    Par iOops dans le forum VB.NET
    Réponses: 9
    Dernier message: 12/03/2013, 19h26
  3. Progress bar et thread
    Par Invité dans le forum C#
    Réponses: 2
    Dernier message: 21/02/2012, 22h49
  4. Progress bar en multi-threading
    Par lestatbzh dans le forum Tkinter
    Réponses: 19
    Dernier message: 07/11/2011, 11h52
  5. Thread, Fenêtre Modal et Progress Bar
    Par Angelinsky7 dans le forum C#
    Réponses: 7
    Dernier message: 24/09/2009, 23h03

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