ASP.NET线程,带参数

本文关键字:参数 线程 NET ASP | 更新日期: 2023-09-27 18:13:13

ASP。NET 3.5 VB.NET

我有一段代码,我想从10个不同的URL中提取PNG图像。

我发现获取每个PNG可能需要2-3秒,所以我认为最好同时获取所有PNG。

有人能帮我调整下面的代码,为每个PNG获取创建一个线程吗?我之前没有做过很多Thread的事情,经过一个小时左右的尝试,我希望能得到一些帮助。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

ASP.NET线程,带参数

创建10个任务,每个任务上的任务数组调用一个异步方法(与处理将图像下载到磁盘的URL的方法相同(等待所有线程返回

var tasks = new List<Task>();
foreach(task in tasks){
task[0] = GetImageAsync();}
Task.WaitAll(tasks.ToArray());

使用Parallel.ForEach简化线程。

如何:写一个简单的平行题。对于每个环路

您可以使用MaxDegreeOfParallelism限制线程数。

Parallel.ForEach(
    lstClsWebsitesImageURLs,
    new ParallelOptions { MaxDegreeOfParallelism = 10 },
    strURL1 => { fAddImageIfSuitable(strURL1); }
);