加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 07:40:40 所属栏目:百科 来源:网络整理
导读:以前一直感觉多线程比较难懂,最近由于需要,没办法必须克服,这不看了几遍书,终于理解差不多了,先把最开始的一个实例弄上来吧。 Imports System.Threading '看名字就知道,这个类干什么用的,多线程应用程序都要用这个类 Public Delegate Function Binary
以前一直感觉多线程比较难懂,最近由于需要,没办法必须克服,这不看了几遍书,终于理解差不多了,先把最开始的一个实例弄上来吧。
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读