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 :

Problème inter-thread ? :/ [Débutant]


Sujet :

VB.NET

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Mai 2012
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mai 2012
    Messages : 5
    Points : 9
    Points
    9
    Par défaut Problème inter-thread ? :/
    Bonjour,

    Je travail actuellement sur une application et celle-ci doit effectuer une vérification de MAJ en arrière plan. Si une mise à jour est détectée, alors, le processus commence le téléchargement et lance l'installation. Jusque là, je n'avait pas de problème. Or j'ai voulus intégrer un système de progressBar et j'avoue être dans le flou total quant aux erreurs se présentant à moi...


    Voici déjà mon appel de la fonction principal :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
     
            ' Activation de la recherche de MAJ en AP
            BackgroundWorker1.WorkerReportsProgress = True
            BackgroundWorker1.WorkerSupportsCancellation = True
            BackgroundWorker1.RunWorkerAsync()
     
        End Sub



    Voilà ensuite le morceau de code incluant mon BackgroundWorker1 avec recherche de MAJ via un fichier TXT :

    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
        Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BackgroundWorker1.DoWork
            'Vérification MAJ
            Dim response As HttpWebResponse = Nothing
            Dim sr As StreamReader = Nothing
     
            Try
                Dim request As HttpWebRequest = CType(WebRequest.Create("https://dl.dropboxusercontent.com/s/6j9hdh7st604ixv/version.txt"), HttpWebRequest)
                response = CType(request.GetResponse, HttpWebResponse)
                sr = New StreamReader(response.GetResponseStream)
                If sr.ReadToEnd <> "0.2.1.0" Then
                    sr.Close()
                    MsgBox(MsgMaj, MsgBoxStyle.Information)
                    Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\setup.exe"
                    If Dir(path) <> "" Then
                        Kill(path)
                    End If
                    Me.ProgressBar1.Visible = True
                    Me.ProgressBar1.Value = 0
                    Me.ProgressBar1.Maximum = 100
                    MAJ = True
                    httpclient = New WebClient
                    httpclient.DownloadFileAsync(New Uri("http://xxxxxxxxxxxxxxxxxxxx.fr/setup.exe"), path)
     
                    Process.Start(path)
                    Application.Exit()
                Else
                    'MsgBox("Logiciel à jour", MsgBoxStyle.Information)
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            Finally
                If Not sr Is Nothing Then sr.Close()
                If Not (response Is Nothing) Then
                    response.Close()
                End If
                If Not (sr Is Nothing) Then
                    sr.Close()
                End If
            End Try
     
        End Sub
     
        Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
            If Me.InvokeRequired Then
                Dim evHandler As DownloadProgressChangedEventHandler = AddressOf BackgroundWorker1_ProgressChanged
                Me.Invoke(evHandler, sender, e)
            Else
                System.Threading.Thread.Sleep(50)
                ProgressBar1.Value = e.ProgressPercentage
                Label1.Text = TryCast(e.UserState, String)
            End If
        End Sub
    J'attends de vous quelques réponses, astuces, informations voir même morceau de codes. Tout me sera utile pour comprendre et intégrer au plus vite un code valide.



    D'avance, merci.

    Cordialement,

    BioSs

  2. #2
    Modérateur
    Avatar de Sankasssss
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2006
    Messages
    1 842
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Novembre 2006
    Messages : 1 842
    Points : 4 232
    Points
    4 232
    Par défaut
    Bonjour,

    Vous ne pouvez pas mettre à jours les composants graphiques sur un autre thread. Le BackGroundworker à une méthode ReportProgress faite pour cela qui sort du Thread secondaire vers le principal.

    Une petite recherche avec BackGroundWorker ProgressBar vb.net donne pas mal d'exemple

  3. #3
    Membre expérimenté
    Homme Profil pro
    Développeur .Net / Delphi
    Inscrit en
    Juillet 2002
    Messages
    738
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Eure (Haute Normandie)

    Informations professionnelles :
    Activité : Développeur .Net / Delphi
    Secteur : Finance

    Informations forums :
    Inscription : Juillet 2002
    Messages : 738
    Points : 1 745
    Points
    1 745
    Par défaut
    Bonjour,

    Je comprends que ça pose problème et la logique me paraît un peu compliquée ...
    Déjà, il est interdit de modifier des controls écran dans le traitement d'un BackgroundWorker :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Me.ProgressBar1.Visible = True
    Me.ProgressBar1.Value = 0
    Me.ProgressBar1.Maximum = 100

    Pour ma part, j'aurais utilisé le BackgroundWorker seulement pour aller rechercher si le download doit être effectué. En effet, la méthode DownloadFileAsync est, comme son nom l'indique, asynchrone.
    Si le BackgroundWorker détecte que le fichier doit être downloadé, tu positionnes une variable à True (ou un code numérique genre zéro si tu veux gérer les erreurs, les dialogBox etc...).
    Ensuite dans le BackgroundWorker.RunWorkerCompleted, tu lances le téléchargement ou affiche une boite de dialogue si besoin.

    En gros :
    Code VB.NET : 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
     
        Private LaunchDownload As Boolean
        Private path As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\setup.exe"
        Private Sub StartCheck()
            ' Activation de la recherche de MAJ en AP
            BackgroundWorker1.WorkerReportsProgress = True
            BackgroundWorker1.WorkerSupportsCancellation = True
            Me.ProgressBar1.Visible = True
            Me.ProgressBar1.Value = 0
            Me.ProgressBar1.Maximum = 100
            BackgroundWorker1.RunWorkerAsync()
        End Sub
     
        Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            ' Toutes les bricoles à faire pour savoir si le fichier doit être downloadé
            LaunchDownload =  True ou False
        End Sub
     
        Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
            If LaunchDownload Then
                Dim httpclient As WebClient
                httpclient = New WebClient
                AddHandler httpclient.DownloadProgressChanged, AddressOf DownloadProgressChange
                AddHandler httpclient.DownloadFileCompleted, AddressOf DownloadFileComplete
                httpclient.DownloadFileAsync(New Uri("http://xxxxxxxxxxxxxxxxxxxx.fr/setup.exe"), path)
            Else
                'Pas de download du fichier 
            End If
     
        End Sub
        Private Sub DownloadProgressChange(sender As Object, e As DownloadProgressChangedEventArgs)
            ProgressBar1.Value = e.ProgressPercentage
        End Sub
        Private Sub DownloadFileComplete(sender As Object, e As AsyncCompletedEventArgs)
            MessageBox.Show("Download Terminé")
            Dim httpClient As WebClient = CType(sender, WebClient)
            RemoveHandler httpclient.DownloadProgressChanged, AddressOf DownloadProgressChange
            RemoveHandler httpclient.DownloadFileCompleted, AddressOf DownloadFileComplete
            Process.Start(path)
            Application.Exit()
        End Sub
    Je n'ai pas testé le code et il y aurait des contrôles d'erreur à ajouter mais c'est pour donner l'idée ...
    Bon courage
    eb.

  4. #4
    Futur Membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Mai 2012
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mai 2012
    Messages : 5
    Points : 9
    Points
    9
    Par défaut Ca marche !
    Merci à vous pour vos indications ! Cela fonctionne parfaitement !

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

Discussions similaires

  1. Réponses: 1
    Dernier message: 21/04/2011, 01h30
  2. [VB.NET] Problème de Thread
    Par Sadneth dans le forum ASP.NET
    Réponses: 26
    Dernier message: 31/01/2006, 10h12
  3. Problème synchronisation threads
    Par Linio dans le forum Concurrence et multi-thread
    Réponses: 19
    Dernier message: 11/01/2006, 16h57
  4. [MFC] Problème de Threads + Timers
    Par Invité dans le forum MFC
    Réponses: 8
    Dernier message: 30/11/2005, 10h51
  5. [VC++6][DX9] Problème de thread lors d'un blit ...
    Par grandjouff dans le forum DirectX
    Réponses: 2
    Dernier message: 12/06/2003, 22h22

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