我有四个并行运行的复杂任务,我想用日志文件更新一个富文本框。 大致的程序结构如下:
Sub buttonClick ()
complextask1 'code goes here
complextask2 'code goes here
complextask3 'code goes here
complextask4 'code goes here
end sub
以上四个任务更新了一个日志文件,我必须在RichTextbox
控件中显示该文件。
我尝试使用无限while
循环,并更新textbox
,但我的UI
正在被绞死。
答案 0 :(得分:0)
您必须在单独的线程或后台工作程序中运行繁重的任务 首先阅读和研究线程,这是一个为您编写任务的示例 将这些导入到您的表单类
Imports System.Threading
Imports System.ComponentModel
在表单中创建一个局部变量
Private syncContext As SynchronizationContext
为您的任务创建方法
Private sub DoTask()
complextask1 'code goes here
complextask2 'code goes here
complextask3 'code goes here
complextask4 'code goes here
End Sub
在按钮上单击“创建新线程并执行繁重任务”
Sub buttonClick ()
syncContext = AsyncOperationManager.SynchronizationContext()
Dim newThread As Thread
newThread = New Thread(AddressOf DoTask)
newThread.Start()
End Sub
要更新您的UI状态,请为其创建一种方法
Private sub UpdateStatus(byval State As Object)
Dim myText As String = CType(State, String)
End Sub
现在调用UI方法在DoTask方法中使用以下语句
Dim NewStatus As String = “This Is New Status”
syncContext.Post(New SendOrPostCallback(AddressOf UpdateStatus), NewStatus)
完整代码将如下所示
Imports System.Threading
Imports System.ComponentModel
Public Class Form1
Private syncContext As SynchronizationContext
Private Sub buttonClick ()
syncContext = AsyncOperationManager.SynchronizationContext()
Dim newThread As Thread
newThread = New Thread(AddressOf DoTask)
newThread.Start()
End Sub
Private sub DoTask()
Dim NewStatus As String
complextask1 'code goes here
NewStatus=”New Task Done”
syncContext.Post(New SendOrPostCallback(AddressOf UpdateStatus), NewStatus)
complextask2 'code goes here
NewStatus=”New Task Done”
syncContext.Post(New SendOrPostCallback(AddressOf UpdateStatus), NewStatus)
complextask3 'code goes here
NewStatus=”New Task Done”
syncContext.Post(New SendOrPostCallback(AddressOf UpdateStatus), NewStatus)
complextask4 'code goes here
NewStatus=”New Task Done”
syncContext.Post(New SendOrPostCallback(AddressOf UpdateStatus), NewStatus)
End Sub
Private sub UpdateStatus(byval State As Object)
Dim myText As String = CType(State, String)
End Sub
End Class