gpt4 book ai didi

vb.net - 在多个线程中运行不同的进程而不会在VB.NET 2中重叠

转载 作者:行者123 更新时间:2023-12-03 13:21:22 25 4
gpt4 key购买 nike

我有一个子过程,我想运行一个不同的过程,具体取决于当前正在运行的过程。我认为最简单的方法是使用每个广告系列详细信息的ArrayList并添加一个“Inuse”字段,以查看Inuse字段设置为0还是1。我遇到的问题是,在运行时这个过程一次完成,并且整数没有在下一个线程启动之前更改,因此我的线程在运行相同的广告系列。

我试图通过在启动线程之间添加Thread.Sleep(100)延迟来避免此问题,但这导致了完全相同的问题。

这是我要执行的操作的一个示例:

    Imports System.Threading

Public Class Form1

Private Campaigns As New ArrayList
Private ProcessRunning As Boolean = False
Friend StopProcess As Boolean = False

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i = 0 To Campaigns.Count - 1
Dim objNewThread As New Thread(AddressOf RunProcess)
objNewThread.IsBackground = True
objNewThread.Start()
Next
End Sub

Private Sub UpdateCells(ByVal CampID As Integer, ByVal Column As String, ByVal newText As String)
Dim CellItemNum As Integer
If Column = "Status" Then CellItemNum = 4
DataGridView2.Rows(CampID).Cells.Item(CellItemNum).Value = newText
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To 10
Campaigns.Add({Campaigns.Count(), "Campaign " & i, "Keywords " & i, "Link " & i, 5, True, 0, 0})
Next
DataGridView2.Rows.Clear()
For Each Campaign In Campaigns
DataGridView2.Rows.Add(New String() {Campaign(1), Campaign(2), Campaign(3), Campaign(6), ""})
Next
End Sub

Private Sub RunProcess()
' Set Variables
Dim CampID As Integer
Dim CampName As String
Dim Keywords As String
Dim Link As String
Dim CheckEvery As Integer
Dim OkToUse As Boolean
Dim Sent As Integer
' Find A Free Campaign
For i As Integer = 0 To Campaigns.Count - 1
' Check If Inuse
If Campaigns(i)(7) = 1 Then Continue For Else Campaigns(i)(7) = 1 ' This Line Sets Campaign To Inuse
' Most of the time only campaign(0) and campaign(1) are selected & multiple threads are running them instead of choosing unique campaigns
' Set Campaign Details
CampID = Campaigns(i)(0)
CampName = Campaigns(i)(1)
Keywords = Campaigns(i)(2)
Link = Campaigns(i)(3)
CheckEvery = Campaigns(i)(4)
OkToUse = Campaigns(i)(5)
Sent = Campaigns(i)(6)
' Start Process
UpdateCells(CampID, "Status", "Looking Up New Links (" & CampID & ")")
Exit For
Next
While StopProcess = False
Thread.Sleep(1000)
UpdateCells(CampID, "Status", "Running Process (" & CampID & ")")
Thread.Sleep(1000)
For i = 0 To CheckEvery
UpdateCells(CampID, "Status", "Re-Checking In " & (CheckEvery - i) & " Seconds")
Thread.Sleep(1000)
Next
End While
' Closing Processes
Campaigns(CampID)(7) = 0
End Sub
End Class

最佳答案

您可以使用SyncLock强制线程等待。

类级别,因此所有线程都访问相同的锁

private myLock as new Object

然后,在您开始过程时使用syncLock,并在完成时结束它。
SyncLock myLock
'process code here
End SyncLock

有关此主题的更多 MSDN信息

关于vb.net - 在多个线程中运行不同的进程而不会在VB.NET 2中重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8855617/

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