前回は EndInvoke メソッドで非同期デリゲート処理の終了待ちをしましたので、今回は、AsyncWaitHandle プロパティの WaitOne メソッドで終了待ちを試してみる事に。(当然、UIスレッドには不向き)。
★元ネタ-マイクロソフトドキュメントで、ほぼそのままのソース。
<注意点>
・WaitHandle は非同期呼び出しが完了すると通知されるので、WaitOne 呼び出しでこれを待機します。
・待機ハンドルの使用終了と同時にシステムリソースを解放する場合、WaitHandle.Close メソッドを呼び出します。
・エラー処理は手抜きです。
お試し環境
Windows7 64bit Edition
Visual Basic 2008 AnyCPU対象
/*-------------------------------- お試し結果 ------------------------------*/
Button2 thread 10 does some work.
Wait Test begins.
The call executed on thread 7, with return value "Wait time was 2000.".
/*----------------------------------------------------------------------------*/
/*---------------------------- お試しソース -------------------------------*/
Public Class Form1
Private Delegate Function dlgtAsyncWaitChk(ByVal tm As Integer, ByRef id As Integer) As String
Private Function waitTest(ByVal term As Integer, ByRef threadId As Integer) As String
Debug.Print("Wait Test begins.")
System.Threading.Thread.Sleep(term)
threadId = System.Threading.Thread.CurrentThread.ManagedThreadId
Return String.Format("Wait time was {0}.", term.ToString())
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim threadId As Integer
Dim awc As dlgtAsyncWaitChk
Dim result As IAsyncResult
Dim retValue As String
awc = New dlgtAsyncWaitChk(AddressOf waitTest)
result = awc.BeginInvoke(2000, threadId, Nothing, Nothing)
Debug.Print("Button2 thread {0} does some work.", System.Threading.Thread.CurrentThread.ManagedThreadId)
result.AsyncWaitHandle.WaitOne()
retValue = awc.EndInvoke(threadId, result)
result.AsyncWaitHandle.Close() ' ガベージコレクションの効率化
Debug.Print("The call executed on thread {0}, with return value ""{1}"".", threadId, retValue)
End Sub
End Class
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/*============================================================================*/