开发者

Why does my progress bar disappear?

开发者 https://www.devze.com 2023-04-01 00:38 出处:网络
I have seen this problem before but I haven\'t seen an answer to the question that applied to my particular case. I have a BackgroundWorker running in my VB form, as well as a progress bar and some la

I have seen this problem before but I haven't seen an answer to the question that applied to my particular case. I have a BackgroundWorker running in my VB form, as well as a progress bar and some labels. I also (if it's important) have a WebBrowser on my form, but it isn't affected by the thread.

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    Dim ints As Integer = Int(InputBox("What number to start at?"))
    Dim inte As Integer = Int(InputBox("What number to end at?"))
    ToolStripStatusLabel1.Text = "0 / " & inte - ints
    ToolStripProgressBar1.Maximum = inte
    ToolStripProgressBar1.Minimum = ints
    ToolStripProgressBar1.Style = ProgressBarStyle.Continuous
    Try
        For z As Integer = ints To inte

            ToolStripProgressBar1.Value = z
            ToolStripStatusLabel1.Text = z & "/" & inte
            'do some stuff here
    catch etc
    next

When the loop i开发者_运维知识库s running, sometimes it stops and the progress bar disappears. Any idea why? Btw the only thing I'm doing in there is running an httpwebrequest and handling the string.


This is likely to do with the fact that you're setting the value of a user interface object (ToolStripProgressBar1) within the BackgroundWorker's DoWork method which is running in it's own thread, separate from the User Interface thread which the ToolStripProgressBar1 is in.

As per the Note on this MSDN page:

You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.

BackgroundWorker events are not marshaled across AppDomain boundaries. Do not use a BackgroundWorker component to perform multithreaded operations in more than one AppDomain.

What you should do is to change the code that's inside the loop (For z As Integer = ints To inte) so that instead of setting the Value and Text properties directly, you call the BackgroundWorker's ReportProgress method. This raises the ProgressChanged event which you can then handle on the main UI thread. It's in here that you can then safely access the properties of User Interface components and objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消