【发布时间】:2010-03-23 05:11:12
【问题描述】:
我正在尝试编写一个 VB.NET 替代 C# 匿名函数。
我希望调用 Threading.SynchronizationContext.Current.Send,它期望将 Threading.SendOrPostCallback 类型的委托传递给它。背景是here,但是因为我希望将字符串传递给MessageBox.Show 并捕获DialogResult,所以我需要在其中定义另一个委托。我在 VB.NET 语法中苦苦挣扎,无论是传统的委托风格还是 lambda 函数。
我对传统语法的看法如下,但我直觉它应该比这简单得多:
Private Sub CollectMesssageBoxResultFromUserAsDelegate(ByVal messageToShow As String, ByRef wasCanceled As Boolean)
wasCanceled = False
If Windows.Forms.MessageBox.Show(String.Format("{0}{1}Please press [OK] to ignore this error and continue, or [Cancel] to stop here.", messageToShow), "Continue", Windows.Forms.MessageBoxButtons.OKCancel, Windows.Forms.MessageBoxIcon.Exclamation) = Windows.Forms.DialogResult.Cancel Then
wasCanceled = True
End If
End Sub
Private Delegate Sub ShowMessageBox(ByVal messageToShow As String, ByRef canceled As Boolean)
Private Sub AskUserWhetherToCancel(ByVal message As String, ByVal args As CancelEventArgs)
If args Is Nothing Then args = New System.ComponentModel.CancelEventArgs With {.Cancel = False}
Dim wasCancelClicked As Boolean
Dim firstDelegate As New ShowMessageBox(AddressOf CollectMesssageBoxResultFromUserAsDelegate)
'…. Now what??
'I can’t declare SendOrPostCallback as below:
'Dim myDelegate As New Threading.SendOrPostCallback(AddressOf firstDelegate)
End Sub
【问题讨论】:
标签: vb.net multithreading delegates lambda backgroundworker