gpt4 book ai didi

vb.net - 这是异步工作的好习惯吗?

转载 作者:行者123 更新时间:2023-12-02 05:42:56 29 4
gpt4 key购买 nike

首先,我在这里搜索并看到了很多类似的问题,但没有一个是我想要的。

我有一个需要一些时间才能返回值的函数为了简化,我们假设它是:

Private Function longProcess() As Boolean
Threading.Thread.Sleep(10000)
Return True
End Function

我想运行它并获取它的值,假设单击 Button1

我尝试了以下代码,它运行良好

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'some stuff
Dim output As Boolean = Await Task.Run(Of Boolean)(Function() longProcess())
'continue another stuff when the longProcess completes
End Sub

这种方式是否足够好?如果没有,可能存在什么问题?

我使用了另一种方法,但由于 Application.DoEvents()

,它使 CPU 使用率更高
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'some stuff
Dim awaiter = Task.Run(Of Boolean)(Function() longProcess()).GetAwaiter()
Do While Not awaiter.IsCompleted
Application.DoEvents()
Loop
Dim output As Boolean = awaiter.GetResult()
'continue another stuff when the longProcess completes
End Sub

最佳答案

根据评论,您的“长时间运行”函数发送http请求,您应该使用“完全”异步方法,而不需要Task.Run提供额外的线程

Private Async Function SendRequest() As Task(Of Boolean)
Using (client As New HttpClient())
client.BaseAddress = new Uri("http://your:api/")

Dim response As HttpResponseMessage = Await client.GetAsync(pathToResource)

Return response.IsSuccessStatusCode
End Using
End Function

然后点击按钮

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'some stuff
Dim output As Boolean = Await SendRequest()
'continue another stuff when the longProcess completes
End Sub

上面的方法比你使用的Task.Run更好,因为当你从另一个线程发送请求时,该线程什么都不做,只是等待响应。通过使用 HttpClient(或其他一些类)的异步 async-await 方法,整个工作将在一个线程上完成,而不会阻塞应用程序的主 UI 线程。

关于 HttpClient 的注意事项:即使在 Using block 中使用的 HttpClient 示例中,您也应该在应用程序生命周期内仅使用一个实例.

来自微软文档:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Especially in server applications, creating a new HttpClient instance for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

关于vb.net - 这是异步工作的好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45897169/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com