如何使用线程加载Bar WinForm?

时间:2013-03-21 15:45:09

标签: vb.net multithreading winforms backgroundworker

我想要一个无限循环进度条,只是为了在长时间加载时给用户一些东西。目前,用户将选择要执行的SQL查询,并将结果显示在包含查询结果的网格视图的另一个winform上。我的目标是让另一个winform(加载表单)上面只有一个进度条,只是无限填充结束并一遍又一遍地重置,直到结果表单上的gridview完成渲染。我尝试了一个后台工作者,因为我认为这需要多线程来提高性能,但负载形式永远不会出现。基本上执行计划应该是这样的:

用户点击执行按钮,在加载表单上显示进度条(无限循环),执行查询并加载结果表单 关闭加载表单上的进度条

从我的主表单

调用上述执行
Private Sub LoadingForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    pbSqlCall.Minimum = 0
    pbSqlCall.Maximum = 100
    pbSqlCall.Step = 10
    Dim Counter As Integer = 0
    While Counter < 100
        pbSqlCall.Increment(10)
        Counter += 10
        If Counter = 100 Then
            Counter = 0
            pbSqlCall.Value = 0
        End If
    End While
End Sub


    BackgroundWorker1.RunWorkerAsync()
    ExecuteQuery(Parameters, Queries.Item(ddlQueries.SelectedIndex))
    'Not sure how to close the form using the thread


Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    lf.ShowDialog() 'Load form
End Sub

1 个答案:

答案 0 :(得分:1)

您可以根据名为“Loader”的表单和名为“Main”的表单

执行以下操作

装载机:

Public Class Loader
    Private Sub Loader_Load(sender As Object, e As EventArgs) Handles MyBase.Load
       pbSqlCall.Style = ProgressBarStyle.Marquee
       pbSqlCall.MarqueeAnimationSpeed = 30
    End Sub
End Class

主:

Imports System.Threading.Tasks
Public Class Main

    Private Sub DoWork_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim lf As New Loader
        lf.Show(Me)

        Task.Factory.StartNew(Sub()
                                  'go get the data for the grid
                                  System.Threading.Thread.Sleep(6000)
                              End Sub) _
                    .ContinueWith(Sub(result As task)
                                      'check the aggregate exception
                                      Dim aex As System.AggregateException = result.Exception
                                      If aex IsNot Nothing Then
                                          MessageBox.Show(String.Format("something bad happened: ", aex.Flatten.Message))
                                      End If

                                      'bind the data to the grid
                                      lf.Close()
                                      lf.Dispose()
                                  End Sub, TaskScheduler.FromCurrentSynchronizationContext)

    End Sub

    Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub
End Class
相关问题