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

前端之家收集整理的这篇文章主要介绍了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

猜你在找的VB相关文章