四种方法在 ComboBox(或其他控件)中加载内容而不冻结容器 Form。
注意:组合框列表不支持 无限 数量的项目。将 65534 元素添加到列表后,下拉菜单实际上会停止工作。
DropDownList 和 ListBox 可以支持更多项目,但这些项目也会在某些时候开始崩溃(~80,000 项目),项目的滚动和呈现会明显受到影响。
在所有这些方法中(除了最后一个,请阅读此处的注释),CancellationTokenSource 用于将 CancellationToken 传递给方法,以表示 - 如果需要 - 已请求取消。
一个方法可以return,当CancellationTokenSource.Cancel()被调用时,检查CancellationToken.IsCancellationRequested属性,或者抛出,调用[CancellationToken].ThrowIfCancellationRequested()。
.Net 接受 CancellationToken 的方法总是抛出。我们可以尝试/捕获调用方法中的OperationCanceledException或TaskCanceledException,以便在执行取消请求时得到通知。
CancellationTokenSource.Cancel() 在表单关闭时也会被调用,以防数据加载仍在运行。
释放时将CancellationTokenSource 设置为null (Nothing):其IsDiposed 属性为内部属性,无法直接访问。
▶ 第一种方法,使用在 UI 线程中创建的 IProgress 委托,用于在从工作线程调用时更新 UI 控件。
Private cts As CancellationTokenSource
Private progress As Progress(Of String())
Private Async Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
cts = New CancellationTokenSource()
progress = New Progress(Of String())(Sub(data) OnProgress(data))
Try
Await GetProductsProgressAsync(progress, cts.Token)
Catch ex As OperationCanceledException
' This exception is raised if cts.Cancel() is called.
' It can be ignored, logged, the User can be notified etc.
Console.WriteLine("GetProductsProgressAsync canceled")
End Try
'Code here is executed right after GetProductsProgressAsync() returns
End Sub
Private Sub OnProgress(data As String())
ComboBox1.BeginUpdate()
ComboBox1.Items.AddRange(data)
ComboBox1.EndUpdate()
End Sub
Private Async Function GetProductsProgressAsync(progress As IProgress(Of String()), token As CancellationToken) As Task
token.ThrowIfCancellationRequested()
' Begin loading data, asynchronous only
' The CancellationToken (token) can be passed to other procedures or
' methods that accept a CancellationToken
' (...)
' If the methods used allow to partition the data, report progress here
' progress.Report([array of strings])
' End loading data
' Otherwise, generate an IEnumerable collection that can be converted to an array of strings
' (or any other collection compatible with the Control that receives it)
progress.Report([array of strings])
End Function
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
CancelTask()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
CancelTask()
End Sub
Private Sub CancelTask()
If cts IsNot Nothing Then
cts.Cancel()
cts.Dispose()
cts = Nothing
End If
End Sub
注意:Form 的FormClosing 事件仅在此处订阅,但同样适用于所有其他方法,当然
Progress<T> 使用方法委托,OnProgress(data As String())。
可以用 Lambda 代替:
' [...]
' Progress<T> can be declared in place
Dim progress = New Progress(Of String())(
Sub(data)
ComboBox1.BeginUpdate()
ComboBox1.Items.AddRange(data)
ComboBox1.EndUpdate()
End Sub)
Await GetProductsProgressAsync(progress, cts.Token)
' [...]
▶ 第二种使用 OleDb 异步方法查询数据库的方法。
所有方法都接受一个 CancellationToken,可用于在任何阶段取消操作。某些操作可能需要一些时间才能取消生效。无论如何,这一切都是异步发生的。
我们可以像以前一样捕获OperationCanceledException 来通知或记录(或任何适合特定上下文的内容)取消。
Private cts As CancellationTokenSource
Private Async Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
cts = New CancellationTokenSource() ' <= Can be used to set a Timeout
Dim connString As String = "<Some connection string>"
Dim sql As String = "<Some Query>"
Try
ComboBox1.DisplayMember = "[A Column Name]"
ComboBox1.ValueMember = "[A Column Name]" ' Optional
ComboBox1.DataSource = Await GetProductsDataAsync(connString, sql, cts.Token)
Catch ocEx As OperationCanceledException
Console.WriteLine("GetProductsDataAsync canceled")
Catch ex As Exception
' Catch exceptions related to data access
Console.WriteLine(ex.ToString())
End Try
'Code here is executed right after GetProductsDataAsync() returns
cts.Dispose()
End Sub
Public Async Function GetProductsDataAsync(connectionString As String, query As String, token As CancellationToken) As Task(Of DataTable)
token.ThrowIfCancellationRequested()
Dim dt As DataTable = New DataTable
Using conn As New OleDbConnection(connectionString),
cmd As New OleDbCommand(query, conn)
Await conn.OpenAsync(token)
dt.Load(Await cmd.ExecuteReaderAsync(token))
End Using
Return dt
End Function
当您需要向异步过程传递一个或多个将来会更新的控件时,可以使用另外两种方法。
您需要确保这些控件在任务执行时可用并且它们的句柄已经创建。
- 具有
Visible = False 的控件或者是从未显示过的 TabContol 的 TabPage 的子控件,不要创建句柄。
▶ 第三种方法,Fire and Forget 风格。任务运行一个从某个源加载数据的方法。加载完成后,将数据设置为 ComboBox.DataSource。
BeginInvoke() 用于在 UI Thread 中执行此操作。没有它,将引发 System.InvalidOperationException 原因为 Illegal Cross-thread Operation。
在设置 DataSource 之前,会调用 BeginUpdate(),以防止 ComboBox 在控件加载数据时重新绘制。 BeginUpdate 通常在一次添加一个项目时调用,以避免闪烁并提高性能,但在这种情况下它也很有用。第二种方法更明显。
Private cts As CancellationTokenSource
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
cts = New CancellationTokenSource()
Task.Run(Function() GetProducts(Me.ComboBox1, cts.Token))
'Code here is executed right after Task.Run()
End Sub
Private Function GetProducts(ctrl As ComboBox, token As CancellationToken) As Task
If token.IsCancellationRequested Then Return Nothing
' Begin loading data, synchronous or asynchrnonous
' The CancellationToken (token) can be passed to other procedures or
' methods that accept a CancellationToken
' Async methods will throw is the Task is canceled
' (...)
' End loading data, synchronous or asynchrnonous
' Synchronous methods don't accept a CancellationToken
' In this case, check again now if we've been canceled in the meanwhile
If token.IsCancellationRequested Then Return Nothing
ctrl.BeginInvoke(New MethodInvoker(
Sub()
ctrl.BeginUpdate()
ctrl.DataSource = [The DataSource]
ctrl.EndUpdate()
End Sub
))
Return Nothing
End Function
▶ 第四种方法使用async / await pattern
Async modifier 被添加到 Form.Shown 事件处理程序中。
将Await Operator应用于Task.Run(),暂停方法中其他代码的执行,直到任务返回,同时将控制权交还给当前线程进行其他操作。
GetProducts() 是一个返回任务的Async 方法,在这种情况下是这样。
Await Task.Run() 调用之后的代码在GetProducts() 返回后执行。
此过程的工作方式与上一个不同:
在这里,假设数据被加载到一个集合中——某种IEnumerable<T>——可能是List<T>,如问题所示。
数据在可用时以120 元素块的形式添加到ComboBox.Items 集合中(不是魔法 数字,它可以调整为与复杂性相关的任何其他值数据)在一个循环中。
Await Task.Yield() 在最后被调用,以符合async/await 的要求。当到达Await 时,它将恢复到捕获的 SynchronizationContext。
这里没有CancellationTokenSource。不是因为不需要使用这种模式,只是因为我认为尝试在方法调用中添加CancellationToken 可能是一个很好的练习,如前面的示例所示,以熟悉。由于此方法使用循环,因此可以在循环中添加取消请求检查,使取消更加有效。
如果数据加载程序使用async 方法,则可以删除Await Task.Yield()。
Private Async Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
Await Task.Run(Function() GetProductsAsync(Me.ComboBox1))
' Code here is executed after the GetProducts() method returns
End Sub
Private Async Function GetProductsAsync(ctrl As ComboBox) As Task
' Begin loading data, synchronous or asynchrnonous
' (...)
' Generates [The List] Enumerable object
' End loading data, synchronous or asynchrnonous
Dim position As Integer = 0
For i As Integer = 0 To ([The List].Count \ 120)
' BeginInvoke() will post to the same Thread here.
' It's used to update the Control in a non-synchronous way
ctrl.BeginInvoke(New MethodInvoker(
Sub()
ctrl.BeginUpdate()
ctrl.Items.AddRange([The List].Skip(position).Take(120).ToArray())
ctrl.EndUpdate()
position += 120
End Sub
))
Next
Await Task.Yield()
End Function