您的位置:首页 > 编程语言 > VB

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

2016-02-24 11:33 120 查看
以前一直感觉多线程比较难懂,最近由于需要,没办法必须克服,这不看了几遍书,终于理解差不多了,先把最开始的一个实例弄上来吧。

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: