VB.net Cross-Thread
I have a cmd command that needs to be executed, when the command starts it starts to fill a progressbar. When the cmd command is done the progressbar needs to fill up to 100.
This is the code i use, but it gives me an error when the progressbar.Value = 100 comes up.
Public Class Form1
Dim teller As Integer
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerProgressbar.Tick
teller += 1
ProgressBar1.Value = teller
If ProgressBar1.Value = ProgressBar1.Maximum Then
TimerProgressbar.Stop()
End If
End Sub
This are the tow commands in another private sub wher开发者_运维技巧e the app is crashing on
ProgressBar1.Value = 100
TimerProgressbar.Stop()
When i debug it and i try it out it crashes on
ProgressBar1.Value = 100
But when i build it under Windows 7 it runs fine without crashing, however a few people reported me it crashes on there Windows xp system.
VB gives me a suggestions about Cross Thread, but i don't know how i could make it work with this.
You can only access (with one exception) a Window's (or anything tied to Window) properties and methods from the thread that created that Window.
But WinForms includes support for this with the Invoke
(and BeginInvoke
) methods to perform a cross thread call, with the InvokeRequired
property.
If InvokeRequired
is true, then you need to use Invoke
to cross threads. To do this wrap your code that manipulates the control in its own method, and either call directly, or via Invoke
. (To perform the operation cross threads asynchronously use BeginInvoke
instead.) Something like:
Private Sub IncrementProgress()
teller += 1
ProgressBar1.Value = teller
If ProgressBar1.Value = ProgressBar1.Maximum Then
TimerProgressbar.Stop()
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerProgressbar.Tick
if ProgressBar1.RequiredInvoke Then
ProgressBar1.Invoke(IncrementProgress)
Else
IncrementProgress
End If
End Sub
精彩评论