the program i'm currently creating has some pictureboxes. The images from these are not added to the resources, instead i want to load them from a website. Its working fine so far, the biggest problem is that the program crashes if it could not load the images. I searched for this problem and it seems that getting the images async would be the right way to solve this problem.
Currently this is the way i'm loading the images:
private static Image GetImageFromURL(string url)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream stream = httpWebReponse.GetResponseStream();
return Image.FromStream(stream);
}
....
foo.Image = GetImageFromURL("https://foo.com/bar.jpg");
I've read many threads on SO and other sites but i still dont understand async. I realy hope someone here can try to explain how to use it if async is the right way to go.
Sorry for my bad english, i hope its not to hard to understand.
In general with the .NET built-in objects (and hopefully by convention with any objects), the "async" version is used by simply using the Async
corresponding method.
For example, instead of this:
HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
You would have this:
HttpWebResponse httpWebReponse = (HttpWebResponse)(await httpWebRequest.GetResponseAsync());
Note the addition of the Async
on the method call, found here, as well as the addition of the await
keyword. This latter change would necessitate a change to the method signature as well:
private static async Task<Image> GetImageFromURL(string url)
And any method which invokes it would have to change as well:
Image someImage = await GetImageFromURL(someUrl);
The asynchronous operation should continue as such all the way to the top level. (The common way of saying this is that it should be "async all the way down".)
Once the method is async
, you can have as many await
operations within it as you like. Some of the other methods you're currently calling may also have Async
equivalents, so you can do the same with them.