委托的同步执行和异步执行(例子)
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
相关文章推荐
- 解决C#中一个"异步方法却同步执行"的问题
- GCD编程dispatch_sync(同步)和dispatch_async(异步)方式执行并发队列任务区别
- GCD的定义及使用详解(同步异步、并发串行、线程间通信、延时执行、只执行一次代码)
- jquery ajax 同步异步的执行
- C# 委托的同步调用和异步调用
- 使用委托异步执行遭遇多个请求时抛异常
- 判断用户的请求类型 get or post 然后同步 或者 异步 执行 方法
- ajax同步、异步执行简单理解与证明
- 异步方法同步执行的帮助类
- ajax回调函数执行顺序带来的同步异步问题
- 同步执行与异步执行
- 「JavaScript」同步、异步、回调执行顺序之经典闭包setTimeout分析
- C#--委托的同步,异步,回调函数
- 并发执行,进程同步,进程互斥,异步,并行,多线程的区别
- 关于同步、异步、阻塞、非阻塞一个通俗易懂的例子
- Go语言同步和异步执行多个任务封装
- C# :线程中操作多控件 (委托实现异步及同步的方法)
- ajax回调函数执行顺序带来的同步异步问题
- GCD使用 串行并行队列 与 同步异步执行的各种组合 及要点分析
- jquery ajax 同步异步的执行