/// <summary> /// Gets an image by the specified uniform resource identifier (URI) asynchronously. /// </summary> /// <param name="uri">A uniform resource identifier (URI) to the image.</param> /// <param name="callback"> /// This method will be called when the downloading operation completed. /// </param> /// <exception cref="System.UriFormatException"/> public void GetImageAsync(string uri, AsyncImageCallback callback) { if (!Uri.IsWellFormedUriString(uri, UriKind.Absolute)) { throw new UriFormatException(); } Uri imageUri; var temp = Uri.TryCreate(uri, UriKind.Absolute, out imageUri); if (!temp) { throw new UriFormatException(); } var fileName = imageUri.Segments.Last(); var fileFullName = Path.Combine(path, fileName); if (memoryCache.ContainsKey(fileName)) { callback(memoryCache[fileName].Clone() as Image); return; } var token = fileFullName.GetHashCode(); if (callbacks.ContainsKey(token)) { callbacks[token].Add(callback); } else { callbacks.Add(token, new List <AsyncImageCallback> { callback }); } try { foreach (var client in clients.Where(c => !c.IsBusy)) { client.DownloadFileAsync(imageUri, fileFullName, fileFullName); return; } var newClient = new WebClient(); newClient.DownloadFileCompleted += client_DownloadFileCompleted; clients.Enqueue(newClient); newClient.DownloadFileAsync(imageUri, fileFullName, fileFullName); } catch (WebException) { callbacks.Remove(token); } }
/// <summary> /// Gets an image by the specified uniform resource identifier (URI) asynchronously. /// </summary> /// <param name="uri">A uniform resource identifier (URI) to the image.</param> /// <param name="callback"> /// This method will be called when the downloading operation completed. /// </param> /// <exception cref="System.UriFormatException"/> public void GetImageAsync(string uri, AsyncImageCallback callback) { if (!Uri.IsWellFormedUriString(uri, UriKind.Absolute)) throw new UriFormatException(); Uri imageUri; var temp = Uri.TryCreate(uri, UriKind.Absolute, out imageUri); if (!temp) throw new UriFormatException(); var fileName = imageUri.Segments.Last(); var fileFullName = Path.Combine(path, fileName); if (memoryCache.ContainsKey(fileName)) { callback(memoryCache[fileName].Clone() as Image); return; } var token = fileFullName.GetHashCode(); if (callbacks.ContainsKey(token)) callbacks[token].Add(callback); else callbacks.Add(token, new List<AsyncImageCallback> { callback }); try { foreach (var client in clients.Where(c => !c.IsBusy)) { client.DownloadFileAsync(imageUri, fileFullName, fileFullName); return; } var newClient = new WebClient(); newClient.DownloadFileCompleted += client_DownloadFileCompleted; clients.Enqueue(newClient); newClient.DownloadFileAsync(imageUri, fileFullName, fileFullName); } catch (WebException) { callbacks.Remove(token); } }