事件模式的非同步作業

摘要:事件模式的非同步作業

這是在知名的程式設計網站"程式設計俱樂部"有人發問的問題。

 

 

01 Public Class 事件模式的非同步作業
02
03     Public Event AsnycCompleteEvent(ByVal sender As Object, ByVal e As WorkAsyncCompletedEventArgs)
04
05
06     Public Sub StartWork()
07         Dim AsyncObj As System.ComponentModel.AsyncOperation = System.ComponentModel.AsyncOperationManager.CreateOperation(Nothing)
08         Dim WorkMethod As New DelWork(AddressOf MainWork)
09
10         WorkMethod.BeginInvoke(New System.AsyncCallback(AddressOf Work_Complete), New Object() {WorkMethod, AsyncObj})
11     End Sub

12
13     Private Delegate Function DelWork() As Integer
14
15     Private Function MainWork() As Integer
16         Dim Rand As New Random
17
18         Threading.Thread.Sleep(10 * 1000)
19
20         Return Rand.Next(0, 100)
21     End Function

22
23     Private Sub Work_Complete(ByVal ar As IAsyncResult)
24         Dim UserObj() As Object = CType(ar.AsyncState, Object())
25         Dim WorkMethod As DelWork = UserObj(0)
26
27         Dim AsyncObj As System.ComponentModel.AsyncOperation = CType(UserObj(1), System.ComponentModel.AsyncOperation)
28         Dim NewValue As Integer = WorkMethod.EndInvoke(ar)
29
30         AsyncObj.PostOperationCompleted(New System.Threading.SendOrPostCallback(AddressOf Me.RaiseCompleteEvent), NewValue)
31
32     End Sub

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

37
38     Public Class WorkAsyncCompletedEventArgs
39         Inherits System.ComponentModel.AsyncCompletedEventArgs
40
41         Sub New(ByVal err As Exception, ByVal Cancelled As Boolean, ByVal NewValue As Integer, ByVal userobj As Object)
42             MyBase.New(err, Cancelled, userobj)
43             Me._NewValue = NewValue
44         End Sub

45
46         Private _NewValue As Integer
47         Public ReadOnly Property NewValue() As Integer
48             Get
49                 Return Me._NewValue
50             End Get
51         End Property
52
53     End Class
54
55 End Class

這裡的程式碼,可以直接COPY就可以使用。若不知用法歡迎提問。若有錯誤歡迎指正。

 不止Know How 還要Know Why