I am trying to load an image from a webserver into a pictureBox. To not block the Form untill the picture is loaded i start a new Thread which works on the LoadPicture()-function till all work is done.
Everything will be started on a MouseHover-Event so it can be triggered multiple times in a short period as the default WindowsHoverTime is 180ms and can't be changed (i searched a lot on that). This is the function:
public void LoadPicture(string url)
{
try
{
WebRequest req = HttpWebRequest.Create(url);
req.Timeout = 3500;
req.Method = "HEAD";
using (WebResponse resp = req.GetResponse())
{
int ContentLength;
if (int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
{
string ContentType = resp.Headers.Get("Content-Type");
if (ContentLength < 1048576 && ContentType == "image/png")
{
this.pictureBox1.Load(url);
}
else
{
this.pictureBox1.Image = mainprogram.Properties.Resources.sample;
}
}
}
}
catch { this.pictureBox1.Image = mainprogram.Properties.Resources.sample; }
}
If the url contains a png-file which is smaller than 1MB it should be loaded into pictureBox1, if not, then a deafult image from resources is loaded.
Thread and calling:
namespace mainprogram
{
public partial class Form1 : Form
{
Thread threadworker;
.
.
.
private void button1_MouseHover(object sender, EventArgs e)
{
if (threadworker.IsAlive == false)
{
threadworker = new Thread(() => LoadPicture(url));
threadworker.Start();
}
}
Now the problem: The thread will fail almost all the time. Catch{} will be executed 9/10 times. Mostly crash at WebResponse resp = req.GetResponse(). If i use the function within the same thread (without starting a new one) it will load just fine, but the GUI will stop responding for like 3seconds untill the picture is loaded.
Edit: It DOES work sometimes, so i am not sure what i am doing wrong.