【问题标题】:Convert Await / Async in .NET 4.5 into .NET 4.0 in Visual Studio 2013 with Microsoft.Bcl.Async使用 Microsoft.Bcl.Async 将 .NET 4.5 中的 Await / Async 转换为 Visual Studio 2013 中的 .NET 4.0
【发布时间】:2014-10-03 15:20:20
【问题描述】:

虽然我有一些脚本编写经验(VBscript、PowerShell、批处理、shell 等),但我不是程序员。我只是要求你请善待!

简短:
作为 VB.NET 的新手,在将 Microsoft.Bcl.Async 包含到项目中之后,我需要帮助将 Await/Async .NET 4.5 代码重写为 .NET 4.0 兼容代码。这是修剪后的 .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 窗体应用程序,带有一些用于用户输入的文本框和两个执行操作的按钮。当按下任一按钮时,它会使用从文本框中提取的参数来执行命令,并在运行时显示一个选框进度条,something I needed help with recently

效果很好,我很激动,非常thankful。但是,我刚刚得知将在上使用的机器只有 .NET 4.0,而且没有时间推出 .NET 4.5。我看到可以在项目中更改目标框架的位置,但是在查看了一些资源(Link 1Link 2Link 3)之后,我不确定如何重新编写代码以与 Microsoft 一起使用。 Bcl.Async。

【问题讨论】:

  • 代码可以编译吗?如果没有,错误是什么?

标签: .net vb.net .net-4.0 visual-studio-2013 async-await


【解决方案1】:

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

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

如果您需要更多建议,Async Sub 方法应仅用作事件处理程序。因此,将RunProcess 定义为返回Task 并从Async Sub buttonName_Click 得到Await 会更合适。更多信息,请查看我的MSDN article on async best practices

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    相关资源
    最近更新 更多