Good day. Trying to download and put an image in Image.
async public void LoadAvatar() { MainWindow.Instance.AvatarLoadBar.Value += 30; byte[] imgbyte = await GetImgByte(); MainWindow.Instance.AvatarLoadBar.Value += 30; Bitmap avatarbit = await ByteToImage(imgbyte); MainWindow.Instance.AvatarLoadBar.Value += 40; ConvertImage(avatarbit); } async public Task<byte[]> GetImgByte() { WebClient ftpClient = new WebClient(); ftpClient.Credentials = new NetworkCredential("*****", "*****"); byte[] imageByte = await ftpClient.DownloadDataTaskAsync(avatar); return await Task.FromResult(imageByte); } where avatar is the image link.
async public static Task<Bitmap> ByteToImage(byte[] blob) { MemoryStream mStream = new MemoryStream(); byte[] pData = blob; mStream.Write(pData, 0, Convert.ToInt32(pData.Length)); Bitmap bm = new Bitmap(mStream, false); mStream.Dispose(); return await Task.FromResult(bm); } public void ConvertImage(Bitmap bmp) { BitmapSource b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height)); MainWindow.Instance.AvatarLoadBar.Visibility =System.Windows.Visibility.Hidden; } I made everything possible asynchronous, but I catch the frieze after the first
MainWindow.Instance.AvatarLoadBar.Value += 30; And then the progress bar disappears and the picture appears. I would like to understand why 2 more cannot work.
MainWindow.Instance.AvatarLoadBar.Value += 30; MainWindow.Instance.AvatarLoadBar.Value += 40;
await Task.Delay(1500)after the second and third change of theProgressBarvalue. 2) I do not understand why to callTask.FromResultif you need to return the result. 3)ByteToImagemethod synchronous. There is no need to screw Task there. 4) UseusinginByteToImage. - Vlad