I created a custom control to display an image. The image displayed must be loaded from a website url. I decided to use Tasks to perform the action asynchronously. This is because many images will be loaded during the operation of my program.
public Image Image {
get => image;
set {
image = value;
Refresh();
}
}
private Image image;
public async void LoadImageAsync(string url)
{
Image = await GetImageAsync(url);
}
private async Task<Image> GetImageAsync(string url)
{
HttpWebRequest request = WebRequest.CreateHttp(url);
var response = await request.GetResponseAsync();
using (var stream = response.GetResponseStream()) {
return Image.FromStream(stream);
}
}
The code above is my current setup. Is this the correct way to use Tasks?
I come from JS and Promises so I've taken my knowledge from there. I tested the method and it appears to run correctly in the background. The result image successfully updates the WinForms UI and the Image
variable is set.