首页 > 解决方案 > 在 winform 中运行 Async/Await 代码时,它会阻止 Winform UI,但在控制台模式下运行时可以工作

问题描述

我创建的一段代码在从控制台应用程序运行时可以正常工作,而当项目是 winform 应用程序时则不能。这是下面的代码,它使用您可以从名为bandwidth 3.1.5的“nuget”中获取的库,该库允许您使用该库调用他们的 rest API 以发送 SMS 测试消息等。我创建了这个函数来运行异步希望在同步模式下运行时解决问题,当从winform应用程序运行时它锁定似乎它在运行异步时也一样,或者我只是没有做正确的事情?

''' <summary>
''' Gets a list of your numbers.
''' </summary>
''' <param name="size">Optional: Used for pagination to indicate the size of each page requested for querying a
''' list of phone numbers. If no value is specified the default value is 25. (Maximum value 1000)</param>
''' <param name="name">Optional: Used to filter the retrieved list of numbers allocated for the authenticated user by it’s name.</param>
''' <param name="applicationId">Optional: Used to filter the retrieved list of numbers by an associated application ID.</param>
''' <param name="state">Optional: Used to filter the retrieved list of numbers allocated for the authenticated user by a US state.</param>
''' <param name="city">Optional: Used to filter the retrieved list of numbers allocated for the authenticated user by it’s city.</param>
''' <param name="numberState">Optional: Used to filter the retrieved list of numbers allocated for
''' the authenticated user by the number state. <seealso cref="Bandwidth.Net.Api.PhoneNumberState"/></param>
''' <returns></returns>
Public Shared Async Function GetListOfPhoneNumbers(ByVal size As Integer?, ByVal name As String, ByVal applicationId As String,
    ByVal state As String, ByVal city As String, ByVal numberState As Api.PhoneNumberState?) As Threading.Tasks.Task(Of List(Of Api.PhoneNumber))

    Dim objClient As New Client(CommonApplication.BandWidth_USER_ID,
        CommonApplication.Bandwidth_API_TOKEN, CommonApplication.Bandwidth_API_SECRET)

    Dim objQuery As New Api.PhoneNumberQuery With
        {
            .Size = size,
            .Name = name,
            .ApplicationId = applicationId,
            .State = state,
            .City = city,
            .NumberState = numberState
        }

    Dim objResponse = Await System.Threading.Tasks.Task.Run(
        Function()
            Dim response = objClient.PhoneNumber.List(objQuery)

            Return response.ToList()
        End Function)

    Return objResponse
End Function

标签: vb.netasync-awaitsynchronization

解决方案


好的,我知道如果其他人遇到同样的问题,您可以通过查看以下内容了解在 winform 中使用时的 async/await:

Stephen Cleary 的异步和等待


推荐阅读