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();
response.GetResponseStream();
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.
CodePudding user response:
First, you should not use the void keyword when you have an async task
Second, you don't need to use the setter to refresh the UI, also is better to use a different name for the Image property.
Third, I suggest using HttpClient instead of WebRequest
public Image MyImage { get; set; }
public async Task LoadImageAsync(string url)
{
MyImage = await GetImageAsync(url);
Refresh();
}
private async Task<Image> GetImageAsync(string url)
{
var httpClint = new HttpClient();
var imageBytes = await httpClint.GetStreamAsync(url);
return Image.FromStream(imageBytes)
}
CodePudding user response:
You're using it properly. Your code illustrates exactly the intended use of async/await: you can write asynchronous code in the same way you would write synchronous code. You've written easy-to-read code that doesn't lock up your UI while waiting for a response. That's your goal.
If you haven't already, read over Microsoft's documentation on Asynchronous programming with async and await
Just a note on your use of HttpWebRequest. The documentation says:
Important
We don't recommend that you use
HttpWebRequestfor new development. Instead, use the System.Net.Http.HttpClient class.
If your code is already written, you can leave it be. I'm pretty sure HttpClient just uses HttpWebRequest in the background anyway. But it's something to think about.
