begin process at 2010 02 10 03:10:42
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

.NET

 > EXEMPLE D'UTILISATION DE CONTROL.INVOKE

EXEMPLE D'UTILISATION DE CONTROL.INVOKE


 Information sur la source

Note :
8,67 / 10 - par 3 personnes
8,67 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :.NET Source .NET ( DotNet ) Classé sous :control, invoke, cross, thread Niveau :Débutant Date de création :25/01/2005 Date de mise à jour :04/05/2008 17:03:12 Vu :24 686

Auteur : coq

Ecrire un message privé
Site perso
Ce membre participe au partage de revenus publicitaires
Commentaire sur cette source (9)
Ajouter un commentaire et/ou une note


 Description

Suite à question(s) sur le forum :

Juste un petit exemple d'utilisation de la méthode Control.Invoke (http://msdn.microsoft.com/fr-fr/library/system.wi ndows.forms.control.invoke.aspx) pour manipuler un contrôle depuis un autre thread que celui qui l'a crée.

Je vous met l'intégralité du code du Form, juste un petit c/c et c'est bon :-)

Source

  • using System;
  • using System.Drawing;
  • using System.Collections;
  • using System.ComponentModel;
  • using System.Windows.Forms;
  • using System.Data;
  • using System.Threading;
  • namespace ControlInvokeSample
  • {
  • public class Form1 : System.Windows.Forms.Form
  • {
  • private System.Windows.Forms.Label label_Affichage;
  • private System.Windows.Forms.Button button_Start;
  • private System.ComponentModel.Container components = null;
  • public Form1()
  • {
  • InitializeComponent();
  • }
  • protected override void Dispose( bool disposing )
  • {
  • if( disposing )
  • {
  • if (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.label_Affichage = new System.Windows.Forms.Label();
  • this.button_Start = new System.Windows.Forms.Button();
  • this.SuspendLayout();
  • //
  • // label_Affichage
  • //
  • this.label_Affichage.Location = new System.Drawing.Point(8, 40);
  • this.label_Affichage.Name = "label_Affichage";
  • this.label_Affichage.Size = new System.Drawing.Size(472, 72);
  • this.label_Affichage.TabIndex = 0;
  • //
  • // button_Start
  • //
  • this.button_Start.Location = new System.Drawing.Point(8, 8);
  • this.button_Start.Name = "button_Start";
  • this.button_Start.TabIndex = 1;
  • this.button_Start.Text = "Start";
  • this.button_Start.Click += new System.EventHandler(this.button_Start_Click);
  • //
  • // Form1
  • //
  • this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
  • this.ClientSize = new System.Drawing.Size(488, 117);
  • this.Controls.Add(this.button_Start);
  • this.Controls.Add(this.label_Affichage);
  • this.Name = "Form1";
  • this.Text = "Form1";
  • this.ResumeLayout(false);
  • }
  • #endregion
  • [STAThread]
  • static void Main()
  • {
  • Application.Run(new Form1());
  • }
  • // ****************
  • // définition du delegate qui sera utilisé
  • private delegate void UpdateLabelDelegate ( string text );
  • // ****************
  • private UpdateLabelDelegate m_upLbl;
  • private Thread m_monThread;
  • private void button_Start_Click(object sender, System.EventArgs e)
  • {
  • button_Start.Enabled = false;
  • // affectation du nom du thread courant
  • Thread.CurrentThread.Name = "Thread principal";
  • // initialisation de l'instance de UpdateLabelDelegate qui sera utilisée dans le thread
  • m_upLbl = new UpdateLabelDelegate(this.MaMethodeDeMajDuLabel);
  • // création et lancement du thread "supplémentaire"
  • m_monThread = new Thread(new ThreadStart(this.ThreadProc));
  • m_monThread.Name = "Thread supplémentaire";
  • m_monThread.Start();
  • }
  • private void ThreadProc()
  • {
  • // le tableau d'object qui sera utilisé pour le passage des paramètres.
  • object [] args = new object[1];
  • for ( int i=0; i<=10; i++)
  • {
  • // affectation du texte, c'est lui qui sera reçu en paramètre "text" de notre méthode
  • args[0] = string.Format("{0} (depuis : {1})", i.ToString(), Thread.CurrentThread.Name);
  • // ****************
  • label_Affichage.Invoke(m_upLbl, args);
  • // ****************
  • // petite pause
  • Thread.Sleep(500);
  • }
  • args[0] = string.Format("C'est fini :-) (depuis : {0})", Thread.CurrentThread.Name);
  • label_Affichage.Invoke(m_upLbl, args);
  • }
  • // ****************
  • // la méthode correspondant à la déclaration de UpdateLabelDelegate
  • // qui fera la MAJ du texte du Label dans le thread auquel appartient le contrôle.
  • private void MaMethodeDeMajDuLabel(string text)
  • {
  • // MAJ du texte en ajoutant le nom du thread depuis lequel cette maj est faite.
  • label_Affichage.Text = string.Format("{0}\r\nLabel mis à jour depuis : {1}", text, Thread.CurrentThread.Name);
  • }
  • // ****************
  • }
  • }
using System; 
using System.Drawing; 
using System.Collections; 
using System.ComponentModel; 
using System.Windows.Forms; 
using System.Data; 
using System.Threading; 
  
namespace ControlInvokeSample 
{ 
    public class Form1 : System.Windows.Forms.Form 
    { 
        private System.Windows.Forms.Label label_Affichage; 
        private System.Windows.Forms.Button button_Start; 
        private System.ComponentModel.Container components = null; 
  
        public Form1() 
        { 
            InitializeComponent(); 
        } 
  
        protected override void Dispose( bool disposing ) 
        { 
            if( disposing ) 
            { 
                if (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.label_Affichage = new System.Windows.Forms.Label(); 
            this.button_Start = new System.Windows.Forms.Button(); 
            this.SuspendLayout(); 
            // 
            // label_Affichage 
            // 
            this.label_Affichage.Location = new System.Drawing.Point(8, 40); 
            this.label_Affichage.Name = "label_Affichage"; 
            this.label_Affichage.Size = new System.Drawing.Size(472, 72); 
            this.label_Affichage.TabIndex = 0; 
            // 
            // button_Start 
            // 
            this.button_Start.Location = new System.Drawing.Point(8, 8); 
            this.button_Start.Name = "button_Start"; 
            this.button_Start.TabIndex = 1; 
            this.button_Start.Text = "Start"; 
            this.button_Start.Click += new System.EventHandler(this.button_Start_Click); 
            // 
            // Form1 
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); 
            this.ClientSize = new System.Drawing.Size(488, 117); 
            this.Controls.Add(this.button_Start); 
            this.Controls.Add(this.label_Affichage); 
            this.Name = "Form1"; 
            this.Text = "Form1"; 
            this.ResumeLayout(false); 
  
        } 
        #endregion 
  
        [STAThread] 
        static void Main() 
        { 
            Application.Run(new Form1()); 
        } 
  
        // **************** 
        // définition du delegate qui sera utilisé 
        private delegate void UpdateLabelDelegate ( string text ); 
        // **************** 
  
        private UpdateLabelDelegate m_upLbl; 
        private Thread m_monThread; 
         
  
        private void button_Start_Click(object sender, System.EventArgs e) 
        { 
            button_Start.Enabled = false; 
             
            // affectation du nom du thread courant 
            Thread.CurrentThread.Name = "Thread principal"; 
  
            // initialisation de l'instance de UpdateLabelDelegate qui sera utilisée dans le thread 
            m_upLbl = new UpdateLabelDelegate(this.MaMethodeDeMajDuLabel); 
             
            // création et lancement du thread "supplémentaire" 
            m_monThread = new Thread(new ThreadStart(this.ThreadProc)); 
            m_monThread.Name = "Thread supplémentaire"; 
            m_monThread.Start(); 
        } 
  
        private void ThreadProc() 
        { 
            // le tableau d'object qui sera utilisé pour le passage des paramètres. 
            object [] args = new object[1]; 
  
            for ( int i=0; i<=10; i++) 
            { 
                // affectation du texte, c'est lui qui sera reçu en paramètre "text" de notre méthode 
                args[0] = string.Format("{0} (depuis : {1})", i.ToString(), Thread.CurrentThread.Name); 
                 
                // **************** 
                label_Affichage.Invoke(m_upLbl, args); 
                // **************** 
                 
                // petite pause 
                Thread.Sleep(500); 
            } 
  
            args[0] = string.Format("C'est fini :-) (depuis : {0})", Thread.CurrentThread.Name); 
            label_Affichage.Invoke(m_upLbl, args); 
        } 
  
        // **************** 
        // la méthode correspondant à la déclaration de UpdateLabelDelegate 
        // qui fera la MAJ du texte du Label dans le thread auquel appartient le contrôle. 
        private void MaMethodeDeMajDuLabel(string text) 
        { 
            // MAJ du texte en ajoutant le nom du thread depuis lequel cette maj est faite. 
            label_Affichage.Text = string.Format("{0}\r\nLabel mis à jour depuis : {1}", text, Thread.CurrentThread.Name);
        } 
        // **************** 
    } 
} 

 Conclusion

Voir aussi le tuto de Mx : http://www.csharpfr.com/tutorial.aspx?ID=174


 Historique

21 novembre 2005 18:13:02 :
ajout des mots clés
11 mars 2006 15:51:19 :
Suppression de quelques horribles concaténations de chaînes ^^
04 mai 2008 17:03:12 :
Changement liens vers MSDN suite au shutdown complet de l'ancienne version (et des redirections).

 Sources du même auteur

Source avec Zip Source avec une capture Source .NET (Dotnet) COQTEXTTOOLS : TRANSFORMATIONS TEXTE SIMPLE ET UTILISATION A...
Source avec Zip Source .NET (Dotnet) XPATH : UTILISEZ DES REQUÊTES PARAMÉTRÉES
Source avec Zip Source .NET (Dotnet) PORTÉE DE LA VALEUR D'UN CHAMP STATIC
Source avec Zip Source .NET (Dotnet) PINVOKE DYNAMIQUE
Source avec Zip Source .NET (Dotnet) MANIPULATION DE LA CORBEILLE (SUPPRESSION, INFORMATIONS, VID...

 Sources de la même categorie

Source avec Zip CHAT SERVER-CLIENT par abderrahmenbilog
Source avec Zip Source avec une capture Source .NET (Dotnet) SIMULATION DE CONSOLE POUR WINDOWS MOBILE par originalcompo
Source avec Zip Source .NET (Dotnet) BASE DE DONNÉES EN XML par DanMor498
Source avec Zip Source avec une capture Source .NET (Dotnet) SIMPLECONV - APPLICATION DE CONVERSION MONÉTAIRE AVEC TAUX E... par Jeffrey_
Source avec Zip Source .NET (Dotnet) TRAITEUR D'IMAGE (MINI) par ycyril

 Sources en rapport avec celle ci

Source avec Zip Source .NET (Dotnet) THREADER SIMPLEMENT UNE CLASSE POUR INTERAGIR AVEC UNE FORM par Yxion
Source avec Zip Source avec une capture Source .NET (Dotnet) THREAD ET PROGRESSBAR - EXEMPLE SIMPLE par MorpionMx
Source avec Zip Source .NET (Dotnet) MODIFICATION DE LA VALEUR D'UN CONTROLE À L'INTERIEUR D'UN T... par bestouinouin
Source .NET (Dotnet) BARRE DE STATUT ET DE PROGRESSION COMPATIBLE MULTITHREAD par cendretp
Source .NET (Dotnet) CROSSTHREADING - APPEL D'UNE MÉTHODE VIA UN DÉLÉGUÉ SYNCHRON... par MorpionMx

Commentaires et avis

Commentaire de JulSoft le 25/01/2005 18:01:12

Merci pour cette source attendue depuis longtemps!!!

Commentaire de LordBob le 06/02/2005 23:42:53

j'en profite pour te remercie d'avoir mis cette source a ma demande :)

Commentaire de coq le 07/02/2005 07:50:44 administrateur CS

de rien :-)

Commentaire de scoubidou944 le 03/07/2007 16:45:32

Avec .NET 2.0 on a le background worker comme objet.
Je suppose que ce dernier est conseillé mais dans quelle mesure ?

Commentaire de scoubidou944 le 03/07/2007 16:57:36

une réponse à rajouter sur le sujet
http://www.csharpfr.com/tutoriaux/CSHARP-OPERATIONS-CROSS-THREADS-UTILISATION-DELEGATIONS-SYNCHRONES-ASYNCHRONES_174.aspx

Commentaire de coq le 03/07/2007 19:26:33 administrateur CS

Ouep, c'est le lien que j'ai mit en "explication finale" ^^

Pour le BackgroundWorker, il faut voir au cas par cas.
Autant l'utiliser à chaque fois qu'il apporte plus d'avantages que d'inconvénients :-)

Commentaire de Bidou le 03/07/2007 22:24:53 administrateur CS

Le backgroundworker est un component que je trouve assez limité.
Personnellement, il fait partie des éléments que j'utilise assez rarement....

Commentaire de scoubidou944 le 04/07/2007 08:50:08

Quels seraient ses inconvénients dans ce contexte précis ?

Commentaire de rzoum14 le 30/08/2007 17:09:48

Merci bien pour cette petite source qui m'a été très utile :)

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Ajout d'un contrôle depuis un thread en utilisant Invoke... [ par gazous ] Bonjour,Je vous contacte car j'ai vu que vous étiez assez calé en dll.Mon problème :J'ai un thread qui essaye d'ajouter un contrôle dans un panel char Thread - Controls [ par bucherb ] Hello!J'ai un petit probl&#232;me.. Je souhaite cr&#233;er un control dans un Thread s&#233;par&#233; du Thread principal... Comment est-ce que je peu Thread et control [ par RMI ] Bonjour, Voila mon probl&#232;me: J'ai une form avec un tabcontrol Les 2 premi&#232;res tabpages sont rempli dans le load du winform la 3&#232;me con Cross-Threading -> Exception [ par sebseb42 ] salut a tousvoila mon probleme est simple, dans ma classe principal, je lance un thread, et dans ce thread j'essaye de modifier un controle.ca fonctio Cross-threading [ par CMatt ] Bonjour, j'ai une application console qui utilise un thread pour &#233;couter des donn&#233;es en provenance d'un socket r&#233;seau. Ce que je voudr Ce qu'on a le droit et pas le droit dans un thread... [ par cyrare ] Bonjour,On voit pas mal de probl&#232;mes li&#233;s au cross threading, et &#224; chacun de ces probl&#232;mes, un rapide tour sur le tuto de ce site Cross thread problème [ par WishhhMaster ] Bonjour,J'ai un petit problème lié au cross threading.  Dans mon application, l'utilisateur choisit divers fichiers images, dont les miniatures sont e Equivalent à Control.Invoke? [ par leprov ] Existe-t-il un équivalent à la méthode control.invoke qui aie la meme fonctionnalité, mais lorsque l'on ne dispose pas d'un controle? c'est plus une c Threading sur le .NET CF [ par t00f ] Bonjour à tous, Je viens vers vous car j'ai une question qui peut paraitre stupide mais sincère : Je cherche a créer un Control personnalisé (type c Thread et création de control [ par Bhaal_DtC ] Tout d'abors je vais r&#233;sumer ma situation le plus clairement possible. j'utilise un thread sp&#233;cifique pour lire des donn&#233;es dans le cad


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 1,045 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales