vb将 .NET 4.5 中的 Await / Async 转换为 Visual Studio 2013 中的 .NET



虽然我有一些脚本经验(VBscript,PowerShell,batch,shell等(我不是程序员。 我只请你善待!

短:
作为 VB.NET 新手,我需要帮助将 Await/Async .NET 4.5 代码重写为 .NET 4.0 兼容代码,将 Microsoft.Bcl.Async 包含在项目中。 下面是经过修剪的工作 .NET 4.5 代码:

Imports System
Imports System.IO
Imports System.Diagnostics
Imports System.Security.Principal
Private Sub buttonName_Click(sender As Object, e As EventArgs) Handles buttonName.Click
   // Do a bunch of stuff
   //   like assign values of text boxes to variables 
   //   validate input to a certain degree
   // Run command
   RunProcess("someexe.exe", "plenty of argments")
End Sub
Private Async Sub RunProcess(ByVal Command As String, Optional ByVal Arguments As String = "NOTSET")
   // Function to disable all the fields and buttons
    LockUI()

   // Sow the progress bar
   // Start the progress marquee so people know something's happening
    ProgressBar1.Visible = True
    ProgressBar1.Style = ProgressBarStyle.Marquee
    ProgressBar1.MarqueeAnimationSpeed = 60
    ProgressBar1.Refresh()

   // Prepare process
   Dim Execute As Process
   If Arguments = "NOTSET" Then
          Execute = Process.Start(Command)
   Else
          Execute = Process.Start(Command, Arguments)
   End If
   // Run the process and wait for it to finish
   Await Task.Run(Sub() Execute.WaitForExit())

   // Do some other stuff like check return code etc.
   // Display positive msgbox for success
   // Display failure message box for, well, failures
   // Hide progress bar since we're done
   ProgressBar1.Visible = False
   // Unlock all the fields
   UnlockUI()
End Sub


长:
我在Visual Studio Premium 2013中为仅控制台/基于命令行的应用程序编写了一个非常简单的GUI包装器。 它实际上只不过是一个VB Windows表单应用程序,其中包含一些用于用户输入的文本框和两个执行操作的按钮。 当按下任一按钮时,它会使用从文本框中提取的参数执行命令,并在运行时显示一个选框进度条,这是我最近需要帮助的。

效果很好,我很激动,也很感激。 但是,我刚刚了解到将用于的计算机只有 .NET 4.0,没有时间推出 .NET 4.5。 我看到我可以在哪里更改项目中的目标框架,但是在查看了一些资源(链接 1、链接 2、链接 3(后,我不确定如何重写代码以使用 Microsoft.Bcl.Async。

Microsoft.Bcl.Async NuGet 包中,许多成员放置在 TaskEx 类型上(因为,当然,NuGet 包无法更改Task类型(。

在您的情况下,您可以将Task.Run更改为 TaskEx.Run .

如果需要更多建议,Async Sub方法应仅用作事件处理程序。因此,将RunProcess定义为返回Task并将其从Async Sub buttonName_Click Await会更合适。有关详细信息,请参阅我的 MSDN 文章有关异步最佳做法。

最新更新