private async Task DoWork(CancellationToken ct) { while (!ct.IsCancellationRequested) { try { var xmlContent = await _webAccessor.DownloadStringAsync(Constants.WallpaperInfoUrl); ct.ThrowIfCancellationRequested(); var info = new BingWallpaperInfo(xmlContent); if (info.PictureUrl != State.PictureUrl || !File.Exists(State.PictureFilePath)) { try { await _webAccessor.DownloadFileAsync(info.PictureUrl, Constants.JpgFile); ct.ThrowIfCancellationRequested(); if (_isJpgSupported) { ChangeWallpager(Constants.JpgFile); } else { ConvertJpgToBmp(Constants.JpgFile, Constants.BmpFile); File.Delete(Constants.JpgFile); ChangeWallpager(Constants.BmpFile); } State.PictureUrl = info.PictureUrl; State.PictureFilePath = _isJpgSupported ? Constants.JpgFile : Constants.BmpFile; State.Copyright = info.Copyright; SaveState(State); OnDownloadCompleted(); } catch (Exception ex) { Log(ex.ToString()); try { foreach (var file in new[] { Constants.JpgFile, Constants.BmpFile }) { if (File.Exists(file)) { File.Delete(file); } } } catch (Exception ex2) { Log(ex2.ToString()); } } } else { if (_firstTime) { ChangeWallpager(State.PictureFilePath); } } } catch (Exception ex) { Log(ex.ToString()); } _firstTime = false; await Task.Delay(TimeSpan.FromMinutes(10), ct); } }
void worker_DoWork(object sender, DoWorkEventArgs e) { if (_worker == null) { return; } if (_worker.CancellationPending) { e.Cancel = true; return; } try { if (_worker.CancellationPending) { e.Cancel = true; return; } var xmlContent = _webAccessor.DownloadString(Constants.WallpaperInfoUrl); if (_worker.CancellationPending) { e.Cancel = true; return; } var info = new BingWallpaperInfo(xmlContent); if (info.PictureUrl != State.PictureUrl || !File.Exists(State.PictureFilePath)) { using (var client = new WebClient()) { try { client.DownloadFile(info.PictureUrl, Constants.JpgFile); if (_worker.CancellationPending) { e.Cancel = true; return; } if (_isJpgSupported) { ChangeWallpager(Constants.JpgFile); } else { ConvertJpgToBmp(Constants.JpgFile, Constants.BmpFile); File.Delete(Constants.JpgFile); ChangeWallpager(Constants.BmpFile); } State.PictureUrl = info.PictureUrl; State.PictureFilePath = _isJpgSupported ? Constants.JpgFile : Constants.BmpFile; State.StartDate = info.StartDate; State.EndDate = info.EndDate; State.Copyright = info.Copyright; SaveState(State); OnDownloadCompleted(); } catch (Exception ex) { Log(ex.ToString()); try { foreach (var file in new[] { Constants.JpgFile, Constants.BmpFile }) { if (File.Exists(file)) { File.Delete(file); } } } catch (Exception ex2) { Log(ex2.ToString()); } } } } else { if (_firstTime) { ChangeWallpager(State.PictureFilePath); } } } catch (Exception ex) { Log(ex.ToString()); } _firstTime = false; GC.Collect(); }