Reputation: 6527
I have a function that loads an image from the internet. Yet, while it is loading, my application can't do anything else. Is there a way around this?
Thanks!
Here is my code:
public static Bitmap BitmapFromWeb(string URL)
{
try
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Bitmap bmp = new Bitmap(myResponse.GetResponseStream());
myResponse.Close();
return bmp;
}
catch (Exception ex)
{
return null;
}
}
private void button1_Click(object sender, EventArgs e)
{
load_avatrar();
}
private void load_avatrar()
{
pictureBox_avatar.Image = BitmapFromWeb(avatral_url);
}
Upvotes: 2
Views: 1812
Reputation: 9312
Using Background worker is definitely a solution. However, the WebRequest class has a support for asynchronous calls. It will also provide better performance by using IO ports.
How to use HttpWebRequest (.NET) asynchronously?
Upvotes: 0
Reputation: 700800
The HttpWebRequest
class har support for this. You can use the BeginGetRequest
method instead of GetRequest
to make an asynchronous call instead.
public static void BitmapFromWeb(string URL, Action<Bitmap> useBitmap) {
try {
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
myRequest.BeginGetResponse(ar => {
HttpWebResponse response = (HttpWebResponse) myRequest.EndGetResponse(ar);
Bitmap bmp = new Bitmap(response.GetResponseStream());
myResponse.Close();
useBitmap(bmp);
});
} catch (Exception ex) {
return;
}
}
private void button1_Click(object sender, EventArgs e) {
load_avatrar();
}
private void load_avatrar() {
BitmapFromWeb(avatral_url, b => pictureBox_avatar.Image = b);
}
Upvotes: 1
Reputation: 273784
Assuming WinForms, you can simply point the picturebox to the source:
pictureBox_avatar.ImageLocation = URL;
Nothing else needed.
Handle the LoadCompleted event to detect errors.
Upvotes: 1
Reputation:
Have a look at BackgroundWorker. It's meant to run exactly these kinds of operations in another thread to free up your application.
UPDATE
Based on your code, you could, with BackgroundWorker, have something like this:
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs args)
{
Bitmap b = BitmapFromWeb("some string");
this.Invoke((MethodInvoker)SOME_METHOD_USING_BITMAP(b));
}
When the bitmap finishes downloading, SOME_METHOD_USING_BITMAP
will be called with the result, and you can update your UI accordingly.
UPDATE 2
SOME_METHOD_USING_BITMAP
will be your load_avatar
method. Have it take a parameter of type Bitmap
:
private void load_avatar(Bitmap avatar)
{
pictureBox_avatar.Image = avatar;
}
Upvotes: 7