预览:Visual Basic与C#中的异步语法

在最近的博客文章中,Visual Basic团队发布了一条简单的消息,声称在Visual Basic和C#中将会增加异步编程语法。两种语言新增的Async和Await关键字的实现将基于.NET 4.0中的任务并行库(Task Parallel Library,TPL)。

Async关键字用于方法,它将启用方法的异步行为。在这个方法中,Await关键字将暂停当前的执行流程,直到当前异步行为结束为止。线程不会因此而暂停,它可以用于处理其他工作,例如UI事件。一旦异步行为结束后,方法的将继续执行余下部分。

以下是一个典型的WPF或WinForm应用程序中的“搜索”功能:

Private Sub SearchButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles SearchButton.Click
    ProgressBar1.Visibility = Visible
    SearchButton.IsEnabled = False

    Dim dt As DataTable = Nothing
    Dim worker As New BackgroundWorker

    AddHandler worker.DoWork, Sub()
        PrepareSearch()
        worker.ReportProgress(50)
        dt = SearchDatabase()
    End Sub

    AddHandler worker.RunWorkerCompleted, Sub()
        ResultsGrid.DataContext = dt
        ProgressBar1.Visibility = Visible
        SearchButton.IsEnabled = True
    End Sub
    
    AddHandler worker.ProgressChanged, 
            Function(a As Object, b As ProgressChangedEventArgs) _
                    ProgressBar1.Value = b.ProgressPercentage

    worker.RunWorkerAsync()
End Sub

根据博文所写,Async VB的版本大约如下所示:

Private Async Sub SearchButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles SearchButton.Click
    ProgressBar1.Visibility = Visible
    SearchButton.IsEnabled = False
    Await PrepareSearch()

    ProgressBar1.Value = 50
    ResultsGrid.DataContext = Await SearchDatabaseAsync()

    ProgressBar1.Visibility = Visible
    SearchButton.IsEnabled = True

End Sub

据称,C#和VB都会享有相同的设计、关键字及单元测试。因此C#版本看上去应该是这样的:

private async void SearchButton_Click(object sender, RoutedEventArgs e) {
    ProgressBar1.Visibility = Visibility.Visible;
    SearchButton.IsEnabled = false;
    await PrepareSearchAsync();

    ProgressBar1.Value = 50;
    ResultsGrid.DataContext = await SearchDatabaseAsync();

    ProgressBar1.Visibility = Visibility.Visible;
    SearchButton.IsEnabled = true;
}

在这些示例中,Async版本会返回一个Task对象。Await关键字后面的代码会形成一个回调函数,在Task完毕后执行。这里您可能想到 CCR类库使用C#的“yield return”来创建continuation的做法。这不是巧合,事实上“await”重用了许多“yield return”代码。于是,VB团队也趁此机会,终于完成了它们的迭代器功能。

我们相信在PDC中将会听到这方面更多信息。

查看英文原文:Sneak Peak: Asynchronous Syntax for Visual Basic and C#

This entry was posted in 未分类. Bookmark the permalink.

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s