2010年5月15日 星期六

事件模式的非同步作業

有一些元件,如fileSystemWatch還有Timer他們主要的工作都是另一個執行緒在作,但是事件卻的觸發卻是在主執行緒上。這個就稱為"事件模式的非同步作業"。

以下為實作:



Public Class  事件模式的非同步作業

     Public Event AsnycCompleteEvent(ByVal sender As Object, ByVal e As WorkAsyncCompletedEventArgs)


     Public Sub StartWork()
Dim AsyncObj As System.ComponentModel.AsyncOperation = System.ComponentModel.AsyncOperationManager.CreateOperation(Nothing)
Dim WorkMethod As New DelWork(AddressOf MainWork)

         WorkMethod.BeginInvoke(New System.AsyncCallback(AddressOf Work_Complete), New Object() {WorkMethod, AsyncObj})
     End Sub

     Private Delegate Function DelWork() As Integer

     Private Function MainWork()As Integer
         Dim Rand As New Random

         Threading.Thread.Sleep(10 * 1000)

         Return Rand.Next(0, 100)
     End Function

     Private Sub Work_Complete(ByVal ar As IAsyncResult)
         Dim UserObj() As Object = CType(ar.AsyncState, Object())
         Dim WorkMethod As DelWork = UserObj(0)

         Dim AsyncObj As System.ComponentModel.AsyncOperation = CType(UserObj(1), System.ComponentModel.AsyncOperation)
         Dim NewValue As Integer = WorkMethod.EndInvoke(ar)

         AsyncObj.PostOperationCompleted(New System.Threading.SendOrPostCallback(AddressOf Me.RaiseCompleteEvent), NewValue)

     End Sub

     Private Sub RaiseCompleteEvent() Sub RaiseCompleteEvent(ByVal state As Object)
         RaiseEvent AsnycCompleteEvent(Me, New WorkAsyncCompletedEventArgs(Nothing, False, CInt(state), Nothing))
     End Sub

     Public Class WorkAsyncCompletedEventArgs
         Inherits System.ComponentModel.AsyncCompletedEventArgs

         Sub New() New(ByVal err As Exception, ByVal Cancelled As Boolean, ByVal NewValue As Integer, ByVal userobj As Object)
             MyBase.New(err, Cancelled, userobj)
             Me._NewValue = NewValue
         End Sub

         Private _NewValue As Integer
         Public ReadOnly Property NewValue() ReadOnly Property NewValue() As Integer
             Get
                 Return Me._NewValue
             End Get
         End Property

     End Class

 End Class

以上程式碼真接copy即可使用。若有謬誤歡迎指正。謝謝

沒有留言:

張貼留言