【问题标题】:How to execute a webrequest asynchronous to parse json如何异步执行 webrequest 以解析 json
【发布时间】:2022-01-02 19:51:18
【问题描述】:

我需要从 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

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

【问题讨论】:

    标签: vb.net asynchronous .net-4.8


    【解决方案1】:

    您可以轻松地使用 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
    

    【讨论】:

      【解决方案2】:

      HttpClientJsonNode 更简单:

      '// 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
      

      【讨论】:

      • 好吧,你从哪里得到 JsonNode?在哪个图书馆?一直说没有声明描述'JsonNode'。由于其保护级别,它可能无法访问。
      • @878757 添加了所需的导入。仅供参考,您可以按Ctrl+. 显示弹出窗口,其中包含添加这些Imports 的建议。
      • 我知道如何查看建议,但您的导入并没有解决任何问题,因为它甚至没有被建议。 Mattia 解决方案就像一个魅力
      • @878757 那么,我的代码有什么错误?我已经对其进行了测试 - 它有效。其他情况是您必须使用可怕的WebClient
      • 之前的错误仍然存​​在,没有改变任何导入的东西。“JsonNode'没有被声明。它可能由于它的保护级别而无法访问。”
      猜你喜欢
      • 2015-01-07
      • 1970-01-01
      • 2021-11-07
      • 2013-01-31
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多