[英]how to prevent vb.net application from lag
我的应用程序变成了一个大应用程序,随着时间的推移具有多种功能,基本上它过滤,并为仓库项目做一些代码,每个部分/流派都有特殊的功能。
所以当我放置文件并单击开始按钮时,它会冻结而不是使用计时器..因为有些文件有超过 3000 行
我如何让等待而不是应用程序冻结,例如 web 应用程序和 Vpns 等大型应用程序。
我的计时器代码是基本的,计算文件行数是最大数,并且在将我的代码应用于每一行后,将 1 添加到变量中:
Private Sub BtnStart_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each line In textbox1.text
#Alot of code
next
dim x as integer= ProgressBar1.value
x += 1
ProgressBar1.value = x
End If
结束子
线程几乎肯定是答案,而且它可能会变得复杂。 几分钟前,我刚刚在另一个问题上发布了一个使用线程的工作示例( richtextbox for = i multiple function )。 该OP希望一次运行2个线程,直到处理完richtextbox中的所有shell命令。
这段代码有效并且正是这样做的; 我希望它至少可以为您提供进一步探索的起点。 根据您的需要,您可以使用WHILE
循环在每个线程完成工作时更新您的进度条。
Imports System.Threading
Public Class Form1
Dim Thread1 As Thread
Dim Thread2 As Thread
Dim Thread1cmd As String = ""
Dim Thread2cmd As String = ""
Dim Thread1Running As Boolean = False
Dim Thread2Running As Boolean = False
Dim LastCmd As Int32 = -1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
LastCmd = -1
While LastCmd < RichTextBox1.Lines.Count
If Thread1Running = False And (LastCmd + 1) < RichTextBox1.Lines.Count Then
LastCmd += 1
Thread1cmd = RichTextBox1.Lines(LastCmd)
output.Text += LastCmd.ToString + " Thread 1: " + Thread1cmd + vbCrLf
Thread1 = New Thread(AddressOf Thread1Helper)
Thread1.IsBackground = True
Thread1.Start()
End If
If Thread2Running = False And (LastCmd + 1) < RichTextBox1.Lines.Count Then
LastCmd += 1
Thread2cmd = RichTextBox1.Lines(LastCmd)
output.Text += LastCmd.ToString + " Thread 2: " + Thread2cmd + vbCrLf
Thread2 = New Thread(AddressOf Thread2Helper)
Thread2.IsBackground = True
Thread2.Start()
End If
'Note - there is debate around the DoEvents that follows, so experiment with it and see what works best for you
Application.DoEvents()
'the main thread now sleeps to give helper threads time to do some work:
System.Threading.Thread.Sleep(200)
End While
End Sub
Sub Thread1Helper()
Thread1Running = True
Dim p1 As System.Diagnostics.Process
Try
p1 = New System.Diagnostics.Process
Dim MyCMD As String = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\cmd"
p1.StartInfo.FileName = MyCMD
p1.StartInfo.Arguments = " /c " + """" + Thread1cmd + "&&PAUSE" + """"
'MsgBox(p1.StartInfo.FileName.ToString)
p1.Start()
p1.WaitForExit()
p1.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Thread1Running = False
End Sub
Sub Thread2Helper()
Thread2Running = True
Dim p2 As System.Diagnostics.Process
Try
p2 = New System.Diagnostics.Process
Dim MyCMD As String = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\cmd"
p2.StartInfo.FileName = MyCMD
p2.StartInfo.Arguments = " /c " + """" + Thread2cmd + "&&PAUSE" + """"
'MsgBox(p2.StartInfo.FileName.ToString)
p2.Start()
p2.WaitForExit()
p2.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Thread2Running = False
End Sub
End Class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.