gpt4 book ai didi

vb.net - 等待单元引发事件

转载 作者:可可西里 更新时间:2023-11-01 02:48:22 25 4
gpt4 key购买 nike

我正在尝试编写一个等待事件发生的代码。我在这个 answer 中使用了答案Tcp 通信页面。 事件 PacketReceived 将在收到数据包时引发。

Private Sub FooBar()
'Send some Tcp Message here`

'Wait until a reply is received here

'Execute some code when reply is received

End Sub

这是代码发送文件名和文件的用途。它缺少文件存在性检查

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim t = New Thread(AddressOf SendFile)
Dim f = New FileAndData
f.FileList = SlideShowItems
f.FileType = "tempSlideShowImage"
t.Start(f)
End Sub

Private Sub SendFile(obj As Object)
Dim fD = CType(obj, FileAndData)
For Each item In fD.FileList.Items
Dim fileIn As New FileStream(item, FileMode.Open)
Const chunkSize = 10485760

Dim messageFileNamePkt As New TcpMessagePacket(Encoding.Default.GetBytes(Path.GetFileName(item)), TcpMessagePacket.PacketHeader.Filename)
messageFileNamePkt.Send(_etcClient.Client) 'Send file name

Dim messageFiletype As New TcpMessagePacket(Encoding.Default.GetBytes(fD.FileType), TcpMessagePacket.PacketHeader.Filetype)
messageFiletype.Send(_etcClient.Client) 'Send file type

'Wait here for reply if for file existence

While fileIn.Position < fileIn.Length
Dim bytes(chunkSize) As Byte
If fileIn.Length - fileIn.Position < bytes.Length Then
ReDim bytes(fileIn.Length - fileIn.Position - 1)
End If
fileIn.Read(bytes, 0, bytes.Length)

Dim messageFilePkt As New TcpMessagePacket(bytes, TcpMessagePacket.PacketHeader.FileData)
messageFilePkt.Send(_etcClient.Client) 'Send file chunks

End While

fileIn.Close()
Dim messageFileEnd As New TcpMessagePacket(Encoding.Default.GetBytes(""), TcpMessagePacket.PacketHeader.TransferComplete)
messageFileEnd.Send(_etcClient.Client) 'Send transfer complete

Next
End Sub

Public Class FileAndData
Public FileList As ListBox
Public FileType As String
End Class

这是回复的处理程序

    Private Sub Client_PacketReceived(sender As Object, e As ExtendedTcpClient.PacketReceivedEventArgs) Handles _etcClient.PacketReceived
End Sub

最佳答案

使用 <a href="https://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(v=vs.110).aspx" rel="noreferrer noopener nofollow">ManualResetEvent</a> .例如。

Imports System.Threading
Module Module1
Private ReadOnly WaitEvent As New ManualResetEvent(True)
Sub Main()
For i = 1 To 100
WaitEvent.WaitOne() 'This is like a door. It's open because of ManualResetEvent(True)
If i = 50 Then
WaitEvent.Reset() 'This closes the door
End If
Console.WriteLine(i)
Next
Console.Read()
End Sub
Private Sub SetTheEventWhenCalled()
WaitEvent.Set() 'This on the other hand, Opens the door
End Sub
End Module

关于vb.net - 等待单元引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40690506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com