章鱼哥出品_VB.NET 线程委托应用实例 一个简单的例子让你轻松掌握委托的用法

时间:2021-10-05 13:56:38

本文就是以最简单的方式让您了解线程和委托的大用法。贴出的代码可直接复制使用,
无需修改或添加,方便读者验证。如有疑问或好的建议请联系我,
废话不多说,上代码,一目了然!
'***************************************************************************
'作者:章鱼哥,QQ:3107073263 群:309816713
'如有疑问或好的建议请联系我,大家一起进步
'主要内容:
'     使用线程和委托
'主要功能:
'    每2秒改变窗体按钮的位置,达到随机跳动的目的
' 实例需要控件:
'      窗体:Form1 按钮:Button1
'***********************************************************************
Imports System.Threading
Public Class Form1
    Private My_Thread As Thread
    Dim r As New Random
    Delegate Sub My_Delegate(ByVal x As Integer, ByVal Y As Integer)

    '第一步,开启线程
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        My_Thread = New Thread(AddressOf Deal_Thread)
        My_Thread.Start()
    End Sub
    '第二步,进入线程处理程序
    Private Sub Deal_Thread()
        While (True)
            Dim x As Integer = r.Next(Me.Width - Button1.Width)
            Dim y As Integer = r.Next(Me.Height - Button1.Height)
            Invoke_Thread(x, y) '使用委托
            Thread.Sleep(2000)
        End While

    End Sub
    '   第三步,给委托传递参数,引发委托
    Private Sub Invoke_Thread(ByVal x As Integer, ByVal Y As Integer)
        Dim hander As New My_Delegate(AddressOf Deal_Delegate)
        Me.Invoke(hander, x, Y)
    End Sub
    '第四部,更新窗体中控件
    Private Sub Deal_Delegate(ByVal x As Integer, ByVal Y As Integer)
        Button1.Location = New Point(x, Y)
    End Sub
    '最后别忘记关掉线程
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        My_Thread.Abort()
    End Sub
End Class


运行效果:

章鱼哥出品_VB.NET 线程委托应用实例 一个简单的例子让你轻松掌握委托的用法