您的位置:首页 > 其它

委托的同步执行和异步执行(例子)

2011-11-03 14:33 513 查看
[转自]地址忘了,请作者见谅.

同步执行

Option Explicit On
Option Strict On

Imports System.Threading

'定义委托
Public Delegate Function BinaryOp(ByVal x As Integer, ByVal y As Integer) As Integer

Module Program
  Sub Main()
    Console.WriteLine("***** Synch Delegate Review *****")
    Console.WriteLine()

    'Print out the ID of the executing thread.
    Console.WriteLine("Main() invoked on thread {0}.", _
      Thread.CurrentThread.ManagedThreadId)

    ' Invoke Add() in a synchronous manner.
    Dim b As BinaryOp = AddressOf Add
    Dim answer As Integer = b(10, 10)'执行委托

    ' These lines will not execute until 
    ' the Add() method has completed.
    Console.WriteLine("Doing more work in Main()!")
    Console.WriteLine("10 + 10 is {0}.", answer)
    Console.ReadLine()
  End Sub

  Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
    ' Print out the ID of the executing thread.
    Console.WriteLine("Add() invoked on thread {0}.", _
      Thread.CurrentThread.ManagedThreadId)

    '  Pause to simulate a lengthy operation.
    Thread.Sleep(5000)
    Return x + y
  End Function
End Module


异步执行

Option Explicit On
Option Strict On

Imports System.Threading

' Our custom delegate. 
Public Delegate Function BinaryOp(ByVal x As Integer, _
ByVal y As Integer) As Integer

Module Program
  Sub Main()
    Console.WriteLine("***** Async Delegate Invocation *****")
    Console.WriteLine()

    ' Print out the ID of the executing thread.
    Console.WriteLine("Main() invoked on thread {0}.", _
      Thread.CurrentThread.ManagedThreadId)

    ' Invoke Add() on a secondary thread.
    Dim b As BinaryOp = New BinaryOp(AddressOf Add)
    Dim itfAR As IAsyncResult = b.BeginInvoke(10, 10, Nothing, Nothing)
'轮询检查是否 执行完毕,其间可作其它工作
    While Not itfAR.AsyncWaitHandle.WaitOne(2000, True)
      ' Do other work on primary thread...
      Console.WriteLine("Doing more work in Main()!")
      Thread.Sleep(1000)
    End While

    ' Obtain the result of the Add() 
    ' method when ready.执行完毕取结果
    Dim answer As Integer = b.EndInvoke(itfAR)
    Console.WriteLine("10 + 10 is {0} .", answer)
    Console.ReadLine()
  End Sub

  Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
    ' Print out the ID of the executing thread.
    Console.WriteLine("Add() invoked on thread {0}.", _
      Thread.CurrentThread.ManagedThreadId)

    '  Pause to simulate a lengthy operation.
    Thread.Sleep(5000)
    Return x + y
  End Function
End Module
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: