前回は AsyncWaitHandle.WaitOne メソッドで非同期デリゲート処理の終了待ちをしましたので、今回は、IsCompleted プロパティで終了待ちを試してみる事に。(UIサービスを提供するスレッド向き?)
★元ネタ-マイクロソフトドキュメントで、ほぼそのままのソース。
<注意点>
・非同期呼び出しの完了を IsCompleted でポーリングすると、スレッドプールで非同期処理を実行しながら、呼出し元スレッドを実行継続できます。
・何れの終了待ちをするにしても、EndInvokeを常に呼び出して、非同期呼出しの完了とします。 ← 重要!
・エラー処理は手抜きです。
お試し環境
Windows7 64bit Edition
Visual Basic 2008 AnyCPU対象
/*-------------------------------- お試し結果 ------------------------------*/
Button3 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 Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.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("Button3 thread {0} does some work.", System.Threading.Thread.CurrentThread.ManagedThreadId)
While Not result.IsCompleted
System.Threading.Thread.Sleep(250)
Debug.Print(".....")
End While
retValue = awc.EndInvoke(threadId, result)
Debug.Print("The call executed on thread {0}, with return value ""{1}"".", threadId, retValue)
End Sub
End Class
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/*============================================================================*/