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

C# Discussion :

Comportement incompréhensible avec thread


Sujet :

C#

  1. #1
    Membre régulier
    Profil pro
    Débutant
    Inscrit en
    Février 2007
    Messages
    127
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Débutant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2007
    Messages : 127
    Points : 87
    Points
    87
    Par défaut Comportement incompréhensible avec thread
    Bonjour à tous, je rencontre un problème que je ne comprend pas avec un code. En effet, je souhaite télécharger une liste de fichier sur internet et mettre à jour un datagridview en fonction du résultat du téléchargement.

    Pour effectuer le téléchargement, j'utilise un array qui stocke les thread et je mets à jour suivant des événements sur le téléchargement.

    Voici le code de la classe filedownloader:

    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
     
     
    using System;
    using System.IO;
    using System.Net;
     
    namespace FileDownloader
    {
     
    	public class FileDownloader
    	{
    		public event _delDownloadStarting DownloadStarting;
    		public event _delDownloadCompleted DownloadCompleted;
     
    		public delegate void _delDownloadStarting(FileDownloader thread);
    		public delegate void _delDownloadCompleted(FileDownloader thread, bool isSuccess);
     
    		private string _DocumentUrl = string.Empty;
    		private string _DirectoryPath = string.Empty;
    		private int _timeoutrequest;
     
    		public bool _IsDownloading = false;
    		public bool _IsDownloadSuccessful = false;
    		private bool _IsStarted = false;
    		public bool _isDownloaded = false;
     
    		public int RowIndex;
     
    		public bool IsStarted
    		{
    			get{return _IsStarted;}
    		}
     
    		private FileDownloader()
    		{}
     
    		public FileDownloader(string documentUrl, string directory, int timeoutrequest = 5000)
    		{
    			_DocumentUrl = documentUrl;
    			_DirectoryPath = directory;
    			_timeoutrequest = timeoutrequest;
    		}
     
    		public string FileName
    		{
    			get
    			{
    				if (_DocumentUrl.Equals(string.Empty))
    					throw new ArgumentException("Please supply a document url.");
     
    				int loc = _DocumentUrl.LastIndexOf("/") + 1;
    				int len = _DocumentUrl.Length - loc;
    				string filename = _DocumentUrl.Substring(loc, len);
    				return filename;
    			}
    		}
     
    		private void IsValid()
    		{
    			if (_DocumentUrl.Equals(string.Empty))
    				throw new ArgumentException("Please supply a document url.");
     
    			if (_DirectoryPath.Equals(string.Empty))
    				throw new ArgumentException("Please supply a directory.");
    		}
     
    		public void StartDownload()
    		{
    			IsValid();
     
    			_IsStarted = true; //TODO: ne passe pas _isStared à true ????????
     
    			DownloadStarting(this);   //raise the download starting event
     
    			_IsDownloading = true;
    			Stream stream = null;
    			FileStream fstream = null;
     
    			try
    			{
    				string destFileName = _DirectoryPath + "\\" + FileName;
    				destFileName = destFileName.Replace("/", " ").Replace("%20", " ");
     
    				if (File.Exists(destFileName) == false)
    				{
    					HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_DocumentUrl);
     
    					request.Timeout = _timeoutrequest;
     
    					HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    					stream = response.GetResponseStream(); //TODO: quid si redirigé????
     
    					byte[] inBuffer = ReadFully(stream, 32768);
     
    					fstream = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Write);
    					fstream.Write(inBuffer, 0, inBuffer.Length);
     
    					fstream.Close();
    					stream.Close();
    				}
    				_IsDownloadSuccessful = true;
    				_IsDownloading = false;
    				_isDownloaded = true;
    			}
    			catch(Exception ex)
    			{
    				_IsDownloadSuccessful = false;
    				_isDownloaded = false;
    			}
    			finally
    			{
    				if (fstream != null) fstream.Close();
    				if (stream != null) stream.Close();
    				DownloadCompleted(this, _IsDownloadSuccessful);
    			}
    		}
     
    		public byte[] ReadFully(Stream stream, int initialLength)
    		{
    			//Code qui fonctionne .....
    		}
    	}
    }
    et la partie du code que j'utilise pour la mise à jour de l'interface et les téléchargements

    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
     
     
    using System;
    using System.Drawing;
    using System.Collections;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Threading;
     
    namespace FileDownloader.Gui
    {
     
    	public partial class Download : UserControl
    	{
    		private const Int16 CELLCOLOR = 0;
    		private const Int16 CELLHREF = 1;
    		private const Int16 CELLSTATUS = 2;
    		private string[] _listfilesTypes = new string[]
     
    		private FileCtrlr _ctrl = new FileCtrlr();
    		private ArrayList _threads = new ArrayList();
    		private ArrayList _instances = new ArrayList();
    		private int _activeDownloadCount = 0;
    		private object _lockObject = new object();
     
    		public Download()
    		{
    			InitializeComponent();
    			CreateHeader();
    			lstBxFiltres.Items.AddRange(_listfilesTypes);
    			btTelecharger.Enabled = false;
    			btAnnuler.Enabled = false;
    		}
     
    		private void Telechargement(string dir)
    		{
    			// TODO: attention à partir de là interdit de réorganiser le datagrid: téléchargera les bon fichier mais n'adaptera pas la bonne ligne pour les info...
    			CreateThreadArray(dtgvListFiles.SelectedRows,dir);
     
    			dtgvListFiles.ClearSelection();
     
    			StartDownload();
    		}
     
    		private void CreateThreadArray(DataGridViewSelectedRowCollection col, string dir)
    		{
    			FileDownloader download = null;
    			Mark m = null;
     
    			foreach (DataGridViewRow row in col)
    			{
    				m = row.Cells[CELLHREF].Tag as Mark;
     
    				row.Cells[CELLSTATUS].Value = "En attente";
     
    				download = new FileDownloader(m.Href, dir);
    				download.RowIndex = row.Index;
    				row.Cells[CELLCOLOR].Tag = download;
     
    				try
    				{
    					ThreadStart tsDelegate = new ThreadStart(download.StartDownload);
     
    					download.DownloadStarting += download_DownloadStarting;
    					download.DownloadCompleted += download_DownloadCompleted;
     
    					Thread t = new Thread(tsDelegate);
     
    					t.Name = row.Cells[CELLHREF].Value.ToString();
    					_threads.Add(t);
    					_instances.Add(download);
    				}
    				catch (Exception ex)
    				{
    					row.Cells[CELLHREF].Style.ForeColor = Color.Red;
    					row.Cells[CELLCOLOR].Style.BackColor = Color.Red;
    					row.Cells[CELLSTATUS].Value = "Erreur : " + ex.Message;			
    				}
    			}
    		}
     
    		private void StartDownload()
    		{
    			int j = 0;
    			int limit = int.Parse(textBox1.Text);
    			int iCount = 0;
     
    			lock (_lockObject)
    				iCount = _instances.Count;
     
    			if (iCount != 0)
    			{
    				foreach (Thread thread in _threads)
    				{
    					FileDownloader file = ((FileDownloader)_instances[j]);
    					if (file.IsStarted == false)
    					{
    						lock (_lockObject)
    						{
    							thread.Start();
    							_activeDownloadCount++;
    						}
    					}
    					if (_activeDownloadCount == limit)
    					{
    						break;
    					}
    					j++;
    				}
    			}
    		}		
     
    		private void download_DownloadStarting(FileDownloader thread)
    		{
    			SetStatus("Telechargement", thread);
    		}
     
    		delegate void delSetStatus(string Status, FileDownloader f);
     
    		private void SetStatus(string Status, FileDownloader f)
    		{
    			if (dtgvListFiles.InvokeRequired)
    			{
    				delSetStatus s = new delSetStatus(SetStatus);
    				this.Invoke(s, new object[] {Status, f});
    			}
    			else
    			{ 
     
    				if(f._isDownloaded == false && f.IsStarted == true) //TODO: a revoir
    				{
    					dtgvListFiles.Rows[f.RowIndex].Cells[CELLSTATUS].Value = "En cours";
    					dtgvListFiles.Rows[f.RowIndex].Cells[CELLCOLOR].Style.BackColor = Color.Blue;
    				}
    				else
    				{
    					if(f._IsDownloadSuccessful)
    					{
    						dtgvListFiles.Rows[f.RowIndex].Cells[CELLSTATUS].Value = "Terminé";
    						dtgvListFiles.Rows[f.RowIndex].Cells[CELLCOLOR].Style.BackColor = Color.Green;
    					}
    					else
    					{
    						dtgvListFiles.Rows[f.RowIndex].Cells[CELLSTATUS].Value = "ERREUR";
    						dtgvListFiles.Rows[f.RowIndex].Cells[CELLHREF].Style.ForeColor = Color.Red;
    						dtgvListFiles.Rows[f.RowIndex].Cells[CELLCOLOR].Style.BackColor = Color.Red;
    					}
    				}
    			}
    		}
     
    		private void download_DownloadCompleted(FileDownloader thread, bool isSuccess)
    		{
    			lock (_lockObject)
    				_activeDownloadCount--;
     
    			SetStatus("Terminé", thread);
    			SetProgressBar();
    			RemoveFromInternalPool(thread);
    			StartDownload();
    		}
     
    		delegate void SetProgressBarCallback();
     
    		private void SetProgressBar()
    		{
    			if (progressBar1.InvokeRequired)
    			{
    				SetProgressBarCallback p = new SetProgressBarCallback(SetProgressBar);
    				this.Invoke(p);
    			}
    			else
    			{
    				lock (_lockObject)
    					progressBar1.Value++;
    			}
    		}
     
    		private void RemoveFromInternalPool(FileDownloader thread)
    		{
    			int i = 0;
    			foreach (FileDownloader f in _instances)
    			{
    				if (f == thread)
    				{
    					lock (_lockObject)// If the file has downloaded, remove it from our pool.
    					{
    						_threads.Remove(_threads[i]);
    						_instances.Remove(f);
    						break;
    					}
    				}
    				i++;
    			}
    		}
     
     
    }
    Le problème se trouve en faite dans la partie SetStatus. je ne parvient pas à intercepter le cas d'une erreur. le mode pas à pas montre que IsSatrted est toujours à false. Comme si la ligne 71 de la class FileDownloader n'était pas prise en compte avant le déclenchement de l’événement DownloadStarting(this).

    Un petit coup de main ne serait pas de refus pour comprendre ce qui se passe car là je ne vois pas du tout....

  2. #2
    Membre expérimenté

    Homme Profil pro
    Responsable des études
    Inscrit en
    Mars 2009
    Messages
    553
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Responsable des études
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2009
    Messages : 553
    Points : 1 672
    Points
    1 672
    Par défaut
    Hello,

    Je viens de passer 10 minutes à essayer de déchiffrer ton code... Disons que tu te rendrais un grand service en réécrivant ta gestion des threads, qui est trop compliquée...
    Du coup, difficile d'émettre un avis sur ce qui ne fonctionne pas comme tu le souhaitais.

    A mon humble avis, l'association entre Thread et FileDownloader est particulièrement bancale, et source potentielle de comportements inattendus.

    Et puis isoler davantage le code qui gère les téléchargements du code qui gère l'interface graphique serait également une bonne idée.

    Et enfin, remplacer tous les booléen "isStarted", "isDownloading", etc... par une enum simplifierait également ton code.

    Et du coup, après tout ça, on y verrait déjà plus clair !

    Bon courage!

  3. #3
    Membre régulier
    Profil pro
    Débutant
    Inscrit en
    Février 2007
    Messages
    127
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Débutant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2007
    Messages : 127
    Points : 87
    Points
    87
    Par défaut
    C'est effectivement ce que j'ai fait....

    Et maintenant ça marche presque parfaitement... Encore l'un ou l'autre petit problème rencontré. Et du coup j'ai encore besoins d'aide.

    Voici mes nouvelles classes :

    La classe du fichier à télécharger :

    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
    	public enum DownloadStatut
    	{
    		Inconnu,
    		Annule,
    		Charge,
    		EnAttente,
    		Demarre,
    		EnCours,
    		Termine,
    		Redirige,
    		TimeOut,
    		Erreur
    	}
     
    	public class FileToDownload
    	{
    		public event delDownloadStarting DownloadStarting;
    		public event delDownloadCompleted DownloadCompleted;
    		public event delDownloadErreur DownloadErreur;
     
    		public delegate void delDownloadStarting(FileToDownload thread);
    		public delegate void delDownloadCompleted(FileToDownload thread);
    		public delegate void delDownloadErreur(FileToDownload thread);
     
    		private string _DocumentUrl = string.Empty;
    		private string _DirectoryPath = string.Empty;
    		private int _timeoutrequest;
     
    		internal DownloadStatut _statutTelechargement = DownloadStatut.Inconnu;
     
    		internal string _error;
     
    		public int RowIndex;
    		public string _proxyUri = string.Empty;
     
    		public string FileName
    		{
    			get
    			{
    				if (_DocumentUrl.Equals(string.Empty))
    					throw new ArgumentException("Please supply a document url.");
     
    				int loc = _DocumentUrl.LastIndexOf("/") + 1;
    				int len = _DocumentUrl.Length - loc;
    				string filename = _DocumentUrl.Substring(loc, len);
    				return filename;
    			}
    		}
     
     
     
    		public FileToDownload(string documentUrl, string directory, int timeoutrequest = 5000, string proxyurl = "")
    		{
    			_DocumentUrl = documentUrl;
    			_DirectoryPath = directory;
    			_timeoutrequest = timeoutrequest;
    			_proxyUri = proxyurl;
    		}
     
     
     
    		public void StartDownload()
    		{
    			IsValid();
     
     
    			_statutTelechargement = DownloadStatut.Demarre;
     
    			if (DownloadStarting != null) DownloadStarting(this);
     
     
    			_statutTelechargement = DownloadStatut.EnCours;
     
    			string destFileName = CreateFileName();
    			bool downloaded = Download(destFileName);
     
    			if(downloaded == true)
    			{
    				_statutTelechargement = DownloadStatut.Termine;
    				if (DownloadCompleted != null) DownloadCompleted(this);
    			}
     
    			else
    			{
    				_statutTelechargement = DownloadStatut.Erreur;
    				if(DownloadErreur != null) DownloadErreur(this);
    			}
     
    		}
     
     
    		private void IsValid()
    		{
    			if (_DocumentUrl.Equals(string.Empty))
    				throw new ArgumentException("Please supply a document url.");
     
     
    			if (_DirectoryPath.Equals(string.Empty))
    				throw new ArgumentException("Please supply a directory.");
    		}
     
     
    		private string CreateFileName()
    		{
    			int count = 1;
     
    			string fileName = FileName;
    			string extension = fileName.Split('.').Last().ToString();
    			string fileNameOnly = fileName.Replace("." + extension, "");
     
    			string path = _DirectoryPath;
    			string newFullPath = Path.Combine(path, FileName);
     
    			while(File.Exists(newFullPath))
    			{
    				string tempFileName = string.Format("{0} ({1})", fileNameOnly, count++);
    				newFullPath = Path.Combine(path, tempFileName + "." + extension);
    			}
     
    			return newFullPath;
    		}
     
     
    		private bool Download(string destFileName)
    		{
    			bool ret;
     
    			Stream stream = null;
    			FileStream fstream = null;
     
    			try {
     
    				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_DocumentUrl);
     
    				request.Timeout = _timeoutrequest;
     
    				IWebProxy proxy = Proxy();
    				if (proxy != null) request.Proxy = proxy;
     
    				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
     
    				if(response.ResponseUri == request.RequestUri)
    				{
    					stream = response.GetResponseStream();
     
    					byte[] inBuffer = ReadFully(stream, 32768);
     
    					fstream = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Write);
    					fstream.Write(inBuffer, 0, inBuffer.Length);
     
    					fstream.Close();
    					stream.Close();
     
    					ret = true;
    				}
    				else
    				{
    					_error = "Lien redirigé vers : ";
    					ret = false;
    				}
    			}
    			catch (Exception ex) //TODO: gerer si timeout pour erreur...
    			{		
    				_error = ex.Message;
    				ret = false;
    			}
    			finally
    			{
    				if(stream != null) stream.Close();
    				if(fstream != null) fstream.Close();
    			}
     
    			return ret;
    		}
     
     
    		private IWebProxy Proxy()
    		{
     
    			IWebProxy proxy = null;
    			if (_proxyUri != null && _proxyUri != string.Empty)
    			{
    				proxy = new WebProxy(_proxyUri, true);
    				proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
    			}
     
    			return proxy;
    		}
     
     
     
    		public byte[] ReadFully(Stream stream, int initialLength)
    		{
    			if (initialLength < 1) // If we've been passed an unhelpful initial length, just use 32K.
    				initialLength = 32768;
     
    			byte[] buffer = new byte[initialLength];
    			int read = 0;
     
    			int chunk;
    			while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
    			{
    				read += chunk;
     
    				if (read == buffer.Length)//If we've reached the end of our buffer, check to see if there's any more information
    				{
    					int nextByte = stream.ReadByte();
     
    					if (nextByte == -1)// End of stream? If so, we're done
    						return buffer;
     
    					byte[] newBuffer = new byte[buffer.Length * 2];// Nope. Resize the buffer, put in the byte we've just read, and continue
    					Array.Copy(buffer, newBuffer, buffer.Length);
    					newBuffer[read] = (byte)nextByte;
    					buffer = newBuffer;
    					read++;
    				}
    			}
     
    			byte[] ret = new byte[read];// Buffer is now too big. Shrink it.
    			Array.Copy(buffer, ret, read);
    			return ret;
    		}
    	}
    La nouvelle classes qui s'occupe des threads des téléchargements...

    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
     
    public class Downloader
    	{		
    		public event _delDownloadsCompleted DownloadsCompleted;
    		public delegate void _delDownloadsCompleted();
     
    		public event _filefinish FileCompleted;
    		public delegate void _filefinish(FileToDownload thread);
     
    		public event _filestarted Filestarted;
    		public delegate void _filestarted(FileToDownload thread);
     
    		public event _fileerreur FileErreur;
    		public delegate void _fileerreur(FileToDownload thread);
     
     
     
    		internal List<FileToDownload> _lstToDownload = new List<FileToDownload>();
    		internal List<FileToDownload> _lstDownloadedOK = new List<FileToDownload>();
    		internal List<FileToDownload> _lstDownloadedErreur = new List<FileToDownload>();
    		private ArrayList _threads = new ArrayList();
    		private ArrayList _instances = new ArrayList();
     
    		internal int _maxThreads = 5;		
    		private int lastdownloadindex = 0;
    		private int _activeDownloadCount = 0;
    		private object _lockObject = new object();		
     
     
    		public Downloader()
    		{}
     
     
     
     
     
    		public void Telechargement(List<Mark> lst)
    		{
     
    		}
     
    		public void StartDownloads(List<FileToDownload> lst, int maxThread = 5)
    		{
    			if(lst.Count == 0 || lst == null)
    			{
    				//TODO:
    			}
    			else
    			{
    				_lstToDownload = lst;
    				_maxThreads = maxThread;
     
    				int FirstIteration = (_maxThreads > lst.Count) ? lst.Count : _maxThreads;
     
    				for (int i = 0; i < FirstIteration-1; i++) {
    					StartDownloadNew();
    				}
    			}
    		}
     
     
     
     
     
    		private void StartDownloadNew()
    		{
     
    			int limit = _maxThreads;
    			int iCount = 0;
     
    			lock (_lockObject)
    			{
    				iCount = _instances.Count;
     
    				if (_activeDownloadCount == limit)
    				{return;}
     
    				if (lastdownloadindex < _lstToDownload.Count)
    				{
    					FileToDownload download = _lstToDownload[lastdownloadindex];
     
    					try
    					{
    						ThreadStart tsDelegate = new ThreadStart(download.StartDownload);
     
    						download.DownloadStarting += download_DownloadStarting;
    						download.DownloadCompleted += download_DownloadCompleted;
    						download.DownloadErreur += download_DownloadErreur;
     
    						Thread t = new Thread(tsDelegate);
     
    						_threads.Add(t);
    						_instances.Add(download);
     
    						t.Start();
     
    						_activeDownloadCount++;
    						lastdownloadindex++;
    					}
    					catch (Exception)
    					{
    						_lstDownloadedErreur.Add(_lstToDownload[lastdownloadindex]);
    					}
     
    				}
    				else
    				{
    					DownloadsFinish();
    				}
     
    			}
     
    		}
     
     
    		private void download_DownloadStarting(FileToDownload thread)
    		{
    			if(Filestarted != null) Filestarted(thread);
    		}
     
    		private void download_DownloadCompleted(FileToDownload thread)
    		{
    			lock (_lockObject)
    				_activeDownloadCount--;
     
    			RemoveFromInternalPool(thread);
    			StartDownloadNew();
     
    			if(FileCompleted != null) FileCompleted(thread);
    		}
     
    		private void download_DownloadErreur(FileToDownload thread)
    		{
    			lock (_lockObject)
    				_activeDownloadCount--;
     
    			RemoveFromInternalPool(thread);
    			StartDownloadNew();
     
    			if(FileErreur != null) FileErreur(thread);
    		}
     
    		private void RemoveFromInternalPool(FileToDownload thread)
    		{
    			int i = 0;
    			foreach (FileToDownload f in _instances)
    			{
    				if (f == thread)
    				{
    					lock (_lockObject)// If the file has downloaded, remove it from our pool.
    					{
    						_threads.Remove(_threads[i]);
    						_instances.Remove(f);
    						break;
    					}
    				}
    				i++;
    			}
    		}
     
    		private void DownloadsFinish()
    		{
    			if(DownloadsCompleted != null) DownloadsCompleted();
    		}
     
    		private void KillThreads()
    		{
    			foreach (Thread t in _threads)
    			{
    				if (t.IsAlive) 
    					t.Abort();
    			}
     
    			_threads = new ArrayList();
    			_instances = new ArrayList();
    			_activeDownloadCount = 0;
    		}
    	}
    Lors de mes test, je demande le téléchargement de 6 fichier par exemples la class downloader en télécharge seulement quelque un. Comme si la class Downloader ne télécharge pas l'ensemble des fichiers.

    Débutant avec les threads, je loupe surement quelque chose. la question étant quoi et/ou qu'elle subtilité je n'ai pas comprise.

    Merci pour l'aide.

  4. #4
    Membre chevronné
    Homme Profil pro
    edi
    Inscrit en
    Juin 2007
    Messages
    898
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : edi

    Informations forums :
    Inscription : Juin 2007
    Messages : 898
    Points : 1 915
    Points
    1 915
    Par défaut
    Tu devrais pour la suite étudier les Task, ainsi que le nouveau pattern async/await (il me semble que François Dorin a fait un tutoriel sur le sujet).

  5. #5
    Membre expérimenté

    Homme Profil pro
    Responsable des études
    Inscrit en
    Mars 2009
    Messages
    553
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Responsable des études
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2009
    Messages : 553
    Points : 1 672
    Points
    1 672
    Par défaut
    @agparchitecture:
    La classe Download est encore trop complexe: multiples listes et index, il y a largement de quoi s'y perdre, et tu dois probablement avoir un loup là-dedans.

    Mon conseil: créer un thread par fichier à téléchargement, puis limiter le nombre de téléchargement simultanés grâce à un Semaphore.

  6. #6
    Membre régulier
    Profil pro
    Débutant
    Inscrit en
    Février 2007
    Messages
    127
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Débutant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2007
    Messages : 127
    Points : 87
    Points
    87
    Par défaut
    Bon après de multiple test, observation, analyse pas à pas, j'ai trouver d’où vient le problème....

    Il s'agit en fait de la classe FileToDownload et non de ma getion des thread (en fait + ou -).

    Le problème survient chaque fois qu'il s'agit de télécharger un fichier qui a le même nom.

    Effectivement, je crée le nom du fichier (avant téléchargement) à écrire avant le téléchargement je télécharge le fichier et puis l'écrit en mode FileMode.openOrCreate. (Ligne 94 class FileToDownload)

    Ce qui fait que si un thread a téléchargé le même fichier avec le même nom sur le disque le fichier est récrit sans donner de nouveau nom.

    Du coup mon affiche est correct pour les informations de téléchargement mais le nombre de fichier écrit n'est pas bon puisque certain thread ont pu réecrire sur le fichier sans en créer un.

    Une petite piste pour comment résoudre le problème?

    @nnovic :
    Merci pour ton aide. J'ai lu les tuto de françois dorin mais j'ai du mal à comprendre et surtout à voir comment appliquer la théorie à mon code.
    Tout comme la class Sémaphore. je vois le but mais j'arrive pas à mettre en oeuvre. Je fais donc +/- ce que fait la classe sémaphore en manuel. D'ou le nombre de tableau et list important...

  7. #7
    Membre expérimenté

    Homme Profil pro
    Responsable des études
    Inscrit en
    Mars 2009
    Messages
    553
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Responsable des études
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2009
    Messages : 553
    Points : 1 672
    Points
    1 672
    Par défaut
    Citation Envoyé par agparchitecture Voir le message
    Ce qui fait que si un thread a téléchargé le même fichier avec le même nom sur le disque le fichier est récrit sans donner de nouveau nom.
    Ta méthode CreateFileName() n'est-elle pas justement prévue pour gérer ce cas de figure ?

  8. #8
    Membre régulier
    Profil pro
    Débutant
    Inscrit en
    Février 2007
    Messages
    127
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Débutant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2007
    Messages : 127
    Points : 87
    Points
    87
    Par défaut
    Si normalement je pensait avoir gérer le problème avec la fonction getFileName mais comme le montre un cas sur le schema ci dessous, le thread B peux voir que le fichier n'existe pas encore au moment de la création du nom. Donc le fichier es réécrit contrairement au thread C qui vois bien un fichier existant.

    Téléchargement fichier avec nom identique par 3 thread

    Thread A ------------------------------------------------------Thread B------------------------------------------------------Thread C

    Je regarde si le fichier existe
    |--------------------------- je regarde si le fichier existe
    |--------------------------- n'existe pas puisque pas encore créer
    | |
    Je télécharge-------------------------------- je télécharge
    | |
    | |
    Je crée le fichier |
    --------------------------------------------------------------------------------------------je regarde si le fichier existe (Existe déjà donc je change le nom)
    --------------------------- j'écris le fichier ---------------------------------------------------------------------------------|
    --------------------------- en remplacant le premier puisque pas encore existant--------------------------------------|
    --------------------------- et même nom que thread D (si mode FileCreate -> erreur)--------------------------------|
    |
    Je télécharge
    |
    |
    Je crée le fichier


    donc le problème vient du moment ou on regarde si le fichier existe ou non.

    j'ai donc corrigé une partie de ma fonction de téléchargement de la manière suivante : Ajout d'un object statick permettant le lock du moment de la vérification du nom du fichier et de sa création. Et la ca marche parfaitement.

    Par contre j'ai pas le sentiment que c'est super propre. Donc je suis preneur pour une autre possibilité plus propre.

    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
    		static object _objectLock = new object();
     
    		private bool Download()
    		{
    			bool ret;
     
    			Stream stream = null;
    			FileStream fstream = null;
     
    			try {
     
    				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_DocumentUrl);
     
    				request.Timeout = _timeoutrequest;
     
    				IWebProxy proxy = Proxy();
    				if (proxy != null) request.Proxy = proxy;
     
    				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
     
    				if(response.ResponseUri == request.RequestUri)
    				{
    					stream = response.GetResponseStream();
     
    					byte[] inBuffer = ReadFully(stream, 32768);
     
    					lock(_objectLock)
    					{
    						fstream = new FileStream(CreateFileName(), FileMode.OpenOrCreate, FileAccess.Write);
    						fstream.Write(inBuffer, 0, inBuffer.Length);
    					}
     
    					fstream.Close();
    					stream.Close();
     
    					ret = true;
    				}
    				else
    				{
    					_error = "Lien redirigé vers : " + response.ResponseUri;
    					ret = false;
    				}
    			}
    			catch (Exception ex) //TODO: gerer si timeout pour erreur...
    			{		
    				_error = ex.Message;
    				ret = false;
    			}
    			finally
    			{
    				if(stream != null) stream.Close();
    				if(fstream != null) fstream.Close();
    			}
     
    			return ret;
    		}

  9. #9
    Membre expérimenté

    Homme Profil pro
    Responsable des études
    Inscrit en
    Mars 2009
    Messages
    553
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Responsable des études
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2009
    Messages : 553
    Points : 1 672
    Points
    1 672
    Par défaut
    Citation Envoyé par agparchitecture Voir le message
    Par contre j'ai pas le sentiment que c'est super propre. Donc je suis preneur pour une autre possibilité plus propre.
    Au contraire, c'est une bonne solution. Personnellement, j'aurai plutôt fait ça à l'intérieur de la méthode CreateFileName(), mais peu importe...

    Par contre, pour chipoter un peu:

    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
     
    if(response.ResponseUri == request.RequestUri)
    {
    	using(stream = response.GetResponseStream())
    	{
    		byte[] inBuffer = ReadFully(stream, 32768);
     
    		lock(_objectLock)
    		{
    			using( fstream = new FileStream(CreateFileName(), FileMode.OpenOrCreate, FileAccess.Write) )
    			{
    				fstream.Write(inBuffer, 0, inBuffer.Length);
    			}
    		}		
    	}
     
    	ret = true;
    }

  10. #10
    Membre régulier
    Profil pro
    Débutant
    Inscrit en
    Février 2007
    Messages
    127
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Débutant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2007
    Messages : 127
    Points : 87
    Points
    87
    Par défaut
    Merci pour l'aide mais afin d'aller jusqu'au bout et parfaire mes connaissance:

    1. Pourquoi plutôt dans le CreateFileName et non ou je l'ai placé?
    2. Pourquoi utiliser un using et non un try catch avec finally?

  11. #11
    Membre expérimenté

    Homme Profil pro
    Responsable des études
    Inscrit en
    Mars 2009
    Messages
    553
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Responsable des études
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2009
    Messages : 553
    Points : 1 672
    Points
    1 672
    Par défaut
    Pourquoi plutôt dans le CreateFileName et non ou je l'ai placé?

    J'ai résonné en terme de "fonctionnalité". C'est la recherche d'un nom de fichier unique qui pose des problèmes de concurrence d'accès, mais une fois que chaque thread a son fichier à lui, techniquement ils peuvent très bien tous écrire simultanément à l'intérieur sans risque d'interférer entre eux.

    Cependant je vois plein de bonne raisons de ne rien changer à ton code: en termes de performances, l'accès au disque dur est un goulet d'étranglement. Il me semble préférable qu'un seul thread à la fois viennent gratter dedans, surtout si les fichiers téléchargés sont volumineux ou si tu comptes augmenter le nombre de threads.

    Pourquoi utiliser un using et non un try catch avec finally?

    Ce n'est pas le même objectif. La clause 'using' est un moyen élégant de s'assurer qu'on n'oublie pas de libérer les ressources que le framework ne sait pas libérer tout seul (méthode Dispose). Idéalement, tout objet qui implémente l'interface IDisposable devrait être encapsulé dans un bloc 'using'.

  12. #12
    Membre régulier
    Profil pro
    Débutant
    Inscrit en
    Février 2007
    Messages
    127
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Débutant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2007
    Messages : 127
    Points : 87
    Points
    87
    Par défaut
    ok merci pour les éclaircissements et pour l'aide.

    pour ceux qui souhaiterais le code complet et fonctionnel

    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
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
     
     
    public enum DownloadStatut
    	{
    		Inconnu,
    		Annule,
    		Charge,
    		EnAttente,
    		Demarre,
    		EnCours,
    		Termine,
    		Redirige,
    		TimeOut,
    		Erreur
    	}
     
    	public class FileToDownload
    	{
    		public event delDownloadStarting DownloadStarting;
    		public event delDownloadCompleted DownloadCompleted;
    		public event delDownloadErreur DownloadErreur;
     
    		public delegate void delDownloadStarting(FileToDownload thread);
    		public delegate void delDownloadCompleted(FileToDownload thread);
    		public delegate void delDownloadErreur(FileToDownload thread);
     
    		private string _DocumentUrl = string.Empty;
    		private string _DirectoryPath = string.Empty;
    		private int _timeoutrequest;
     
    		internal DownloadStatut _statutTelechargement = DownloadStatut.Inconnu;
     
    		internal string _error;
     
    		public int RowIndex;
    		public string _proxyUri = string.Empty;
     
    		public string FileName
    		{
    			get
    			{
    				if (_DocumentUrl.Equals(string.Empty))
    					throw new ArgumentException("Please supply a document url.");
     
    				int loc = _DocumentUrl.LastIndexOf("/") + 1;
    				int len = _DocumentUrl.Length - loc;
    				string filename = _DocumentUrl.Substring(loc, len);
    				return filename;
    			}
    		}
     
     
     
    		public FileToDownload(string documentUrl, string directory, int timeoutrequest = 5000, string proxyurl = "")
    		{
    			_DocumentUrl = documentUrl;
    			_DirectoryPath = directory;
    			_timeoutrequest = timeoutrequest;
    			_proxyUri = proxyurl;
    		}
     
     
     
    		public void StartDownload()
    		{
    			IsValid();
     
     
    			_statutTelechargement = DownloadStatut.Demarre;
     
    			if (DownloadStarting != null) DownloadStarting(this);
     
     
    			_statutTelechargement = DownloadStatut.EnCours;
     
    			bool downloaded = Download();
     
    			if(downloaded == true)
    			{
    				_statutTelechargement = DownloadStatut.Termine;
    				if (DownloadCompleted != null) DownloadCompleted(this);
    			}
     
    			else
    			{
    				_statutTelechargement = DownloadStatut.Erreur;
    				if(DownloadErreur != null) DownloadErreur(this);
    			}
     
    		}
     
     
    		private void IsValid()
    		{
    			if (_DocumentUrl.Equals(string.Empty))
    				throw new ArgumentException("Please supply a document url.");
     
     
    			if (_DirectoryPath.Equals(string.Empty))
    				throw new ArgumentException("Please supply a directory.");
    		}
     
     
    		private string CreateFileName()
    		{
    			int count = 1;
     
    			string fileName = FileName;
    			string extension = fileName.Split('.').Last().ToString();
    			string fileNameOnly = fileName.Replace("." + extension, "");
     
    			string path = _DirectoryPath;
    			string newFullPath = Path.Combine(path, FileName);
     
    			while(File.Exists(newFullPath))
    			{
    				string tempFileName = string.Format("{0} ({1})", fileNameOnly, count++);
    				newFullPath = Path.Combine(path, tempFileName + "." + extension);
    			}
     
    			return newFullPath;
    		}
     
    		static object _objectLock = new object();
     
    		private bool Download()
    		{
    			bool ret;
     
    			Stream stream = null;
    			FileStream fstream = null;
     
    			try {
     
    				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_DocumentUrl);
     
    				request.Timeout = _timeoutrequest;
     
    				IWebProxy proxy = Proxy();
    				if (proxy != null) request.Proxy = proxy;
     
    				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
     
    				if(response.ResponseUri == request.RequestUri)
    				{
    					stream = response.GetResponseStream();
     
    					byte[] inBuffer = ReadFully(stream, 32768);
     
    					lock(_objectLock)
    					{
    						fstream = new FileStream(CreateFileName(), FileMode.OpenOrCreate, FileAccess.Write);
    						fstream.Write(inBuffer, 0, inBuffer.Length);
    					}
     
    					fstream.Close();
    					stream.Close();
     
    					ret = true;
    				}
    				else
    				{
    					_error = "Lien redirigé vers : " + response.ResponseUri;
    					ret = false;
    				}
    			}
    			catch (Exception ex) //TODO: gerer si timeout pour erreur...
    			{		
    				_error = ex.Message;
    				ret = false;
    			}
    			finally
    			{
    				if(stream != null) stream.Close();
    				if(fstream != null) fstream.Close();
    			}
     
    			return ret;
    		}
     
     
    		private IWebProxy Proxy()
    		{
     
    			IWebProxy proxy = null;
    			if (_proxyUri != null && _proxyUri != string.Empty)
    			{
    				proxy = new WebProxy(_proxyUri, true);
    				proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
    			}
     
    			return proxy;
    		}
     
     
     
    		public byte[] ReadFully(Stream stream, int initialLength)
    		{
    			if (initialLength < 1) // If we've been passed an unhelpful initial length, just use 32K.
    				initialLength = 32768;
     
    			byte[] buffer = new byte[initialLength];
    			int read = 0;
     
    			int chunk;
    			while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
    			{
    				read += chunk;
     
    				if (read == buffer.Length)//If we've reached the end of our buffer, check to see if there's any more information
    				{
    					int nextByte = stream.ReadByte();
     
    					if (nextByte == -1)// End of stream? If so, we're done
    						return buffer;
     
    					byte[] newBuffer = new byte[buffer.Length * 2];// Nope. Resize the buffer, put in the byte we've just read, and continue
    					Array.Copy(buffer, newBuffer, buffer.Length);
    					newBuffer[read] = (byte)nextByte;
    					buffer = newBuffer;
    					read++;
    				}
    			}
     
    			byte[] ret = new byte[read];// Buffer is now too big. Shrink it.
    			Array.Copy(buffer, ret, read);
    			return ret;
    		}
    	}
     
    public class Downloader
    	{		
    		public event _delDownloadsCompleted DownloadsCompleted;
    		public delegate void _delDownloadsCompleted();
     
    		public event _filefinish FileCompleted;
    		public delegate void _filefinish(FileToDownload thread);
     
    		public event _filestarted Filestarted;
    		public delegate void _filestarted(FileToDownload thread);
     
    		public event _fileerreur FileErreur;
    		public delegate void _fileerreur(FileToDownload thread);
     
     
     
    		internal List<FileToDownload> _lstToDownload = new List<FileToDownload>();
    		internal List<FileToDownload> _lstDownloadedOK = new List<FileToDownload>();
    		internal List<FileToDownload> _lstDownloadedErreur = new List<FileToDownload>();
    		private ArrayList _threads = new ArrayList();
    		private ArrayList _instances = new ArrayList();
     
    		internal int _maxThreads = 5;		
    		private int lastdownloadindex = 0;
    		private int _activeDownloadCount = 0;
    		private object _lockObject = new object();		
     
     
    		public Downloader()
    		{}
     
     
    		private void Reset()
    		{
    			_lstToDownload = new List<FileToDownload>();
    			_lstDownloadedOK = new List<FileToDownload>();
    			_lstDownloadedErreur = new List<FileToDownload>();
    			_threads = new ArrayList();
    			_instances = new ArrayList();
     
    			_maxThreads = 5;
    			lastdownloadindex = 0;
    			_activeDownloadCount = 0;
    			_lockObject = new object();
    		}
     
     
    		public void StartDownloads(List<FileToDownload> lst, int maxThread = 5)
    		{
    			if(lst.Count == 0 || lst == null)
    			{
    				//TODO:
    			}
    			else
    			{
    				Reset();
     
    				_lstToDownload = lst;
    				_maxThreads = maxThread;
     
    				int FirstIteration = (_maxThreads > lst.Count) ? lst.Count : _maxThreads;
     
    				for (int i = 0; i < FirstIteration; i++) {
    					StartDownload();
    				}
    			}
    		}
     
     
     
     
     
    		private void StartDownload()
    		{
     
    			int limit = _maxThreads;
    			int iCount = 0;
     
    			lock (_lockObject)
    			{
    				iCount = _instances.Count;
     
    				if (_activeDownloadCount == limit)
    				{return;}
     
    				if (lastdownloadindex < _lstToDownload.Count)
    				{
    					FileToDownload download = _lstToDownload[lastdownloadindex];
     
    					try
    					{
    						ThreadStart tsDelegate = new ThreadStart(download.StartDownload);
     
    						download.DownloadStarting += download_DownloadStarting;
    						download.DownloadCompleted += download_DownloadCompleted;
    						download.DownloadErreur += download_DownloadErreur;
     
    						Thread t = new Thread(tsDelegate);
     
    						_threads.Add(t);
    						_instances.Add(download);
     
    						t.Start();
     
    						_activeDownloadCount++;
    						lastdownloadindex++;
    					}
    					catch (Exception)
    					{
    						_lstDownloadedErreur.Add(_lstToDownload[lastdownloadindex]);
    					}
     
    				}
    				else
    				{
    					//DownloadsFinish();
    				}
     
    			}
     
    		}
     
     
    		private void download_DownloadStarting(FileToDownload thread)
    		{
    			if(Filestarted != null) Filestarted(thread);
    		}
     
    		private void download_DownloadCompleted(FileToDownload thread)
    		{
    			lock (_lockObject)
    				_activeDownloadCount--;
     
    			RemoveFromInternalPool(thread);
    			StartDownload();
     
    			if(FileCompleted != null) FileCompleted(thread);
    		}
     
    		private void download_DownloadErreur(FileToDownload thread)
    		{
    			lock (_lockObject)
    				_activeDownloadCount--;
     
    			RemoveFromInternalPool(thread);
    			StartDownload();
     
    			if(FileErreur != null) FileErreur(thread);
    		}
     
    		private void RemoveFromInternalPool(FileToDownload thread)
    		{
    			int i = 0;
    			foreach (FileToDownload f in _instances)
    			{
    				if (f == thread)
    				{
    					lock (_lockObject)// If the file has downloaded, remove it from our pool.
    					{
    						_threads.Remove(_threads[i]);
    						_instances.Remove(f);
    						break;
    					}
    				}
    				i++;
    			}
    		}
     
    		private void DownloadsFinish() //TODO: quand et ou le déclencher???
    		{
    			if(DownloadsCompleted != null) DownloadsCompleted();
    		}
     
    		public void Cancel()
    		{
    			//TODO: changer la liste des fichier annulé...
    			KillThreads();
    		}
     
    		public void Pause()
    		{
     
    		}
     
    		private void KillThreads()
    		{
    			foreach (Thread t in _threads)
    			{
    				if (t.IsAlive) 
    					t.Abort();				
    			}
     
    			_threads = new ArrayList();
    			_instances = new ArrayList();
    			_activeDownloadCount = 0;
    		}
    	}

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

Discussions similaires

  1. [TRANSAQ SQL] INSERT comportement bizarre avec les REAL
    Par argyronet dans le forum Langage SQL
    Réponses: 2
    Dernier message: 02/12/2005, 11h47
  2. [SWING] Exception bizarre avec Thread
    Par Gob4 dans le forum Débuter
    Réponses: 2
    Dernier message: 13/09/2005, 21h55
  3. [MFC] Cherche Timer avec thread
    Par romeo9423 dans le forum MFC
    Réponses: 17
    Dernier message: 09/03/2005, 10h33
  4. Variable static avec thread
    Par oxor3 dans le forum Threads & Processus
    Réponses: 7
    Dernier message: 27/08/2004, 11h45
  5. incompréhension avec ado
    Par Orgied dans le forum Bases de données
    Réponses: 3
    Dernier message: 19/05/2004, 18h24

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