I'm writing a program that uses an API which crawls the web to fetch pieces of information. I am then showing the results on an HTML Document (Excel was an option, but due to some restrictions and features I opted for an Html Document)
Long story short, the request result often have links to an image and I need to show them to the user. The problem is that sometimes some images don't exist anymore.
The basic is as follow:
string carouselItems = "";
for (int i = 0; i < imgs.Count; i++)
{
if (i == 0)
carouselItems += $"" +
$"<div class=\"carousel-item active\">" +
$" <img src = \"" + imgs[i] + "\" class=\"d-block w-100\" alt=\"Bild "
+ (i + 1).ToString() + " von " + imgs.Count.ToString()
+ "\" onerror=\"this.style.display = 'none'\">" +
$" <div class=\"carousel-caption d-none d-md-block\">" +
$" <p>Bild " + (i + 1).ToString() + "</p>" +
$" </div>" +
$"</div>";
else
carouselItems += $"" +
$"<div class=\"carousel-item\">" +
$" <img src = \"" + imgs[i] + "\" class=\"d-block w-100\" alt=\"Bild "
+ (i + 1).ToString() + " von " + imgs.Count.ToString()
+ "\" onerror=\"this.style.display = 'none'\">" +
$" <div class=\"carousel-caption d-none d-md-block\">" +
$" <p>Bild " + (i + 1).ToString() + "</p>" +
$" </div>" +
$"</div>";
}
I thought to make an HttpRequest
to the link and to hold on only to those images that returned a content type of "image", because sometime some links redirect me to a website (probably because the image doesn't exist anymore), like this:
for (int i = 0; i < line.Bild.Count; i++)
{
var client = new RestClient(line.Bild[i]);
var request = new RestRequest(Method.GET);
client.FollowRedirects = true;
request.AddHeader("Accept", "image/*");
var res = client.Execute(request);
if (res.ContentType.Contains("image/")) images.Add(line.Bild[i]);
}
This approach is fine, but "slow" whenever I have hundreds of images to check. What I would like to achieve is some form of parallelization for which all images are checked at the same time and I am returned with a list of unbroken images. I am not so good with asynchronous coding that's why I need some help.
I will be happy to read your answers! BR