开发者

Multi threading in C# while downloading an image from the internet

I have a function that loads an image from the internet. Yet, while i开发者_如何学JAVAt 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);
}


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;
}


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.


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);
}


You can use BackgroundWorker class to download the image asynchronously. Here is the link to the msdn page Here is the good tutorial.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜