ASP.NET 3.5 VB.NET
我有代码,我想从10个不同的URL中获取PNG图像。
我发现获取每个PNG最多可能需要2-3秒才能认为最好同时获取所有PNG。
有人可以通过调整下面的代码为每个PNG抓取制作一个线程来帮助我吗?在尝试一小时左右之前和之后我没有做过很多线程的东西我希望得到一些帮助。 TIA
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Drawing.Drawing2D
Public Class TestImageSuggestionsCreate
Dim intClsWidthMaximumAllowed As Integer = 600
Dim intClsHeightMaximumAllowed As Integer = 400
Dim intClsWidthMinimumAllowed As Integer = 200
Dim intClsHeightMinimumAllowed As Integer = 200
Dim strClsImageOriginalURL As String = ""
Dim lstClsWebsitesImageURLs As New List(Of String)
Public Function fWebsitesImageSuggestionsCreate() As Boolean
'Load URLS strings into class List variable: lstClsWebsitesImageURLs
fWebsitesImageURLSuggestionsGet()
'Go through each URL and download image to disk
For Each strURL1 As String In lstClsWebsitesImageURLs
'This needs to be done in a separate thread
'(Up to 10 threads):
fAddImageIfSuitable(strURL1)
Next
End Function
Private Function fWebsitesImageURLSuggestionsGet() As Boolean
Dim strURL As String = ""
strURL = "https://upload.wikimedia.org/wikipedia/en/thumb/f/f7/Sheraton_Hotels.svg/1231px-Sheraton_Hotels.svg.png"
lstClsWebsitesImageURLs.Add(strURL)
strURL = "http://wall--art.com/wp-content/uploads/2014/10/sheraton-logo-png.png"
lstClsWebsitesImageURLs.Add(strURL)
'Up to 10 strURL items
'.............
End Function
Private Function fAddImageIfSuitable(ByVal strImageURL As String) As Boolean
'Get bitmap from URL
Dim btmImage1 As Bitmap = New Bitmap(fGetStreamBitmap(strImageURL))
'Don't add if image too small
If btmImage1.Width < intClsWidthMinimumAllowed Or _
btmImage1.Height < intClsHeightMinimumAllowed Then
Exit Function
End If
'Save image to disk here
'..............
End Function
Private Function fGetStreamBitmap(ByVal strURL As String) As Bitmap
Try
Dim request As System.Net.WebRequest = System.Net.WebRequest.Create(strURL)
Dim response As System.Net.WebResponse = request.GetResponse()
Dim responseStream As System.IO.Stream = response.GetResponseStream()
Dim btmBitmap1 As New Bitmap(responseStream)
Return btmBitmap1
Finally
End Try
End Function
End Class
答案 0 :(得分:1)
使用Parallel.ForEach
进行简化线程。
How to: Write a Simple Parallel.ForEach Loop
您可以使用MaxDegreeOfParallelism
限制主题数。
Parallel.ForEach(
lstClsWebsitesImageURLs,
new ParallelOptions { MaxDegreeOfParallelism = 10 },
strURL1 => { fAddImageIfSuitable(strURL1); }
);
答案 1 :(得分:1)
在每个Task上创建10个任务,任务数组调用异步方法(处理URL以将图像下载到磁盘的方法相同) 等待所有线程返回
var tasks = new List<Task>();
foreach(task in tasks){
task[0] = GetImageAsync();}
Task.WaitAll(tasks.ToArray());