【IT168 评论】在最近的博客文章中,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
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的版本大约如下所示:
ProgressBar1.Visibility = Visible
SearchButton.IsEnabled = False
Await PrepareSearch()
ProgressBar1.Value = 50
ResultsGrid.DataContext = Await SearchDatabaseAsync()
ProgressBar1.Visibility = Visible
SearchButton.IsEnabled = True
End Sub
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;
}
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团队也趁此机会,终于完成了它们的迭代器功能。