如何异步执行 webrequest 来解析 json

How to execute a webrequest asynchronous to parse json

我需要从 API 中获取一个值,我正在使用以下同步代码。

       Dim request As HttpWebRequest
       Dim response As HttpWebResponse = Nothing
       Dim reader As StreamReader

       Try

           request = DirectCast(WebRequest.Create("http://ecc"), HttpWebRequest)

           response = DirectCast(request.GetResponse(), HttpWebResponse)
           reader = New StreamReader(response.GetResponseStream())

           Dim rawresp As String
           rawresp = reader.ReadToEnd()

           Dim jResults As JObject = JObject.Parse(rawresp)
           Label1.Text = jResults("result").ToString()


       Catch ex As Exception
           MsgBox(ex.ToString)
       Finally
           If Not response Is Nothing Then response.Close()

       End Try

问题是它是同步的,我想让它异步,以免同时冻结表单。 我怎样才能异步它?

使用 HttpClient and JsonNode 更简单:

'// Web API:
'// app.MapGet("/api", () => new { id = 1, result = "100", name = "name1" });

Imports System.Net.Http
Imports System.Text.Json.Nodes

Using http = New HttpClient
  Dim url = "https://localhost:5000/api"
  Dim json = JsonNode.Parse(Await http.GetStreamAsync(url))
  Label1.Text = json("result")
End Using

您可以轻松地使用 WebClient 和 nuget 包 NewtonSoft 执行如下操作:

Imports System.IO
Imports System.Net
Imports System.Text
Imports Newtonsoft.Json

Public Class Form1
    Private ReadOnly wc As New WebClient()

 Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        'stop timer to avoid simultaneous I/O operations
        Timer1.Stop()

        Dim downloadTasks As New List(Of Task(Of String))

        'download api and add as a task of string
        Dim APIValue = wc.DownloadStringTaskAsync("https://api.etc")
        downloadTasks.Add(Value)
        Await Task.WhenAll(downloadTasks)
        Dim d = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(APIValue.Result)

        Dim Price As String = d("result").ToString
        Label1.Text = Price

        Timer1.Start()
 End Sub
 End Class