vb.net多线程同步调用实例

以前一直感觉多线程比较难懂,最近由于需要,没办法必须克服,这不看了几遍书,终于理解差不多了,先把最开始的一个实例弄上来吧。
Imports System.Threading   '看名字就知道,这个类干什么用的,多线程应用程序都要用这个类

Public Delegate Function BinaryOp(ByVal x As Integer, ByVal y As Integer) As Integer
Module Module1

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

        ' 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 New BinaryOp(AddressOf Add)

        ' Could also write b. Invoke(10, 10);   注意区别 同步方式是invoke,已不是beginInvoke
        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
    Private 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

不知道大家怎么理解这个同步和异步。反正这个不大好理解,我觉得主要就看是否有阻塞或者尽可能小的阻塞。特别是同步调用方式和同步调用线程的区别,特别是很多翻译过来的东西,最好还是看原文和实例。
---------------------------一以下异步调用代码----------------------------------------------------
Imports System.Threading   '看名字就知道,这个类干什么用的,多线程应用程序都要用这个类
Public Delegate Function BinaryOp(ByVal x As Integer, ByVal y As Integer) As Integer

Module Module1
    Sub main()

        Console.WriteLine("***** Async Delegate Invocation *****")

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

        Dim b As New BinaryOp(AddressOf Add)
        Dim iftAR As IAsyncResult = b.BeginInvoke(10, 10, Nothing, Nothing)

        ' This message will keep printing until
        ' the Add() method is finished.
        Do While Not iftAR.IsCompleted  
            Console.WriteLine("Doing more work in Main()!")
            Thread.Sleep(1000)
        Loop

        ' Now we know the Add() method is complete.
        Dim answer As Integer = b.EndInvoke(iftAR)

        Console.WriteLine("10 + 10 is {0}.", answer)
        Console.ReadLine()
    End Sub

    Private 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值