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

[转自]地址忘了,请作者见谅.


同步执行

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值