如何使用backgroundworker

时间:2018-05-28 09:07:00

标签: vb.net progress-bar backgroundworker

每个人,我更新了我的问题,我只是Visual Basic.Net和Oracle存储过程的新手。

我在互联网上找到了这组代码。它可以工作但是,如何使用Oracle存储过程从数据库中获取行来转换此导入CSV文件。

    Dim strRow As String()              'String array to read all fields in a row
Dim dblAmount As Double             'Variable for total amount 
Dim blnReported As Boolean = True   'Flag to check progress report completed or not

'Create TextFieldParser class to parse the stock.csv file in the current location
Dim txtFile As FileIO.TextFieldParser

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'Allow background operation to be cancelled
    bgWorker.WorkerSupportsCancellation = True

    'Allow background operation to report progress
    bgWorker.WorkerReportsProgress = True

    'Disable Stop Button. It is enabled only after start
    'button is pressed
    btnStop.Enabled = False

    'set status message
    lblStatus.Text = "Press Start to import data from csv."

    'Add columns to the grid
    dgvCSVData.Columns.Add("colNo", "No")
    dgvCSVData.Columns("colNo").Width = 30
    dgvCSVData.Columns.Add("colDate", "Date")
    dgvCSVData.Columns("colDate").Width = 60
    dgvCSVData.Columns.Add("colItem", "Item")
    dgvCSVData.Columns("colItem").Width = 120
    dgvCSVData.Columns.Add("colQty", "Quantity")
    dgvCSVData.Columns("colQty").Width = 50
    dgvCSVData.Columns.Add("colUnit", "Unit")
    dgvCSVData.Columns("colUnit").Width = 30
    dgvCSVData.Columns.Add("colAmt", "Amt")
    dgvCSVData.Columns("colAmt").Width = 60
End Sub

Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
    'Disable Start button and Enable Stop
    btnStart.Enabled = False
    btnStop.Enabled = True

    'set status message
    lblStatus.Text = "Importing data from CSV file."

    'Start time-consuming operation in background
    Call bgWorker.RunWorkerAsync()
End Sub

Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
    'Enable Start button and disable Stop
    btnStart.Enabled = True
    btnStop.Enabled = False

    'Stop background operation
    bgWorker.CancelAsync()

    'set status message
    lblStatus.Text = "Import cancelled. Press Start again."
End Sub

Private Sub bgWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker.DoWork
    Dim intCount As Int16 = 0
    txtFile = New FileIO.TextFieldParser("stock.csv")
    'Specify structure of the file
    txtFile.TextFieldType = FileIO.FieldType.Delimited
    txtFile.SetDelimiters(",")

    'Skip header row
    txtFile.ReadFields()

    'Start reading data from file
    While Not txtFile.EndOfData

        If bgWorker.CancellationPending Then
            e.Cancel = True
            Exit Sub

        Else

            'Wait for Progress Report to finish
            While Not blnReported
                Application.DoEvents()
            End While

            'Read all field in a row into a string array
            strRow = txtFile.ReadFields()

            'Do some calculations and assign value to data grid
            dblAmount = CDbl(strRow(3)) * CDbl(strRow(4))

            'Add some sleep to simulate a long running operation
            System.Threading.Thread.Sleep(500)

            'Progress report pending
            blnReported = False

            'increment counter
            intCount += 1

            'Report the progress
            bgWorker.ReportProgress(10, intCount)

        End If

    End While
End Sub

Private Sub bgWorker_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgWorker.ProgressChanged
    'Copy values to data grid
    dgvCSVData.Rows.Add(strRow)
    dgvCSVData.Rows(dgvCSVData.CurrentRow.Index - 1).Cells("colAmt").Value = dblAmount

    pgbCopyProgress.Value = e.UserState
    'Progress report finished
    blnReported = True
End Sub

Private Sub bgWorker_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgWorker.RunWorkerCompleted
    If e.Cancelled Or Not IsNothing(e.Error) Then
        'Clear the data grid
        dgvCSVData.Rows.Clear()
    Else
        'Progress completed
        pgbCopyProgress.Value = 100

        'Release txtfile
        txtFile.Dispose()
        btnStop.Enabled = False
        btnStart.Enabled = True

    End If
End Sub

这是我调用数据库中行的代码

 Public Function RESA_Checker(ByVal stores As String, ByVal bus_date As String, ByVal warehouse As String)
    dt = New DataTable
    bg.GetProcDataTable(connStr, "SALES_CHECKER.procedure_checker")
    cmd.Parameters.Add(New OracleParameter("stores", OracleDbType.Varchar2)).Value = stores
    cmd.Parameters.Add(New OracleParameter("bus_date", OracleDbType.Varchar2)).Value = bus_date
    cmd.Parameters.Add(New OracleParameter("warehouse", OracleDbType.Varchar2)).Value = warehouse
    cmd.Parameters.Add(New OracleParameter("O_OUTPUT", OracleDbType.RefCursor)).Direction = ParameterDirection.Output
    adap_or.SelectCommand = cmd
    adap_or.Fill(dt)


    Return dt
    ora_conn.Close()
End Function

我的目的是通过带有进度条或动画gif的对话框通知用户,表单正在加载并仍然从数据库中提取记录,并且等待" /"在考虑表单崩溃的情况下搜索"并防止对用户造成混淆。

P.S。如果给出视频教程的链接会很有帮助。 我希望你能帮助我,谢谢。

1 个答案:

答案 0 :(得分:0)

注意:您已经更改了问题(您应该创建一个新问题而不是更改旧问题)并且我不熟悉Oracle,所以此信息现在可能无关紧要。

和你一样,我也是一个noobie,但我们可以解决这个问题。有很多方法可以做到这一点,所以我列出了一些。如果没有人抓你的痒,希望他们会指出你正确的方向。我也看到你知道背景工作者是什么,所以我假设你知道它是如何工作的,或者可以找到自己想出来的资源(如果不是我将下面的一些资源链接到它)。

<强>进度:

您可以在整个按钮的流程中增加一个进度条,以表明该过程尚未结束。

下面,当按下按钮时,它会在列表中搜索字符串&#34; Snow White&#34;。如果它在列表中检查的当前字符串不是&#34;白雪公主&#34; ProgressBar1递增以显示已检查移动标题。这将循环直到&#34;白雪公主&#34;字符串来了。然后我们的循环将显示一个完整的ProgressBar1并显示&#34;找到它!&#34;

示例代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim moviesList As New List(Of String) From {"Cinderella", "Snow White", "Rapunzel"}
    ProgressBar1.Maximum = moviesList.Count()
    For Each movie In moviesList
        If movie = "Snow White" Then
            ProgressBar1.Value = ProgressBar1.Maximum
            Label1.Text = "Found it!"
        Else
            ProgressBar1.Value += 1
        End If
    Next
End Sub

<强>标签:

您可以显示一个标签,告诉用户该按钮的流程在处理完毕之前仍在处理。

下面,当按下按钮时,它会在列表中搜索字符串&#34; Snow White&#34;并将Label1设置为&#34; Loading ...&#34;。如果它在列表中检查的当前字符串不是&#34;白雪公主&#34;它会继续像往常一样,如果它是&#34;白雪公主&#34;它会将Label1更新为&#34;找到它!&#34;。通过显示这个,用户可以看到程序是否正在加载。

示例代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim moviesList As New List(Of String) From {"Cinderella", "Snow White", "Rapunzel"}
    Label1.Text = "Loading..."
    For Each movie In moviesList
        If movie = "Snow White" Then
            Label1.Text = "Found it!"
        End If
    Next
End Sub

动画Gif:

您可以在按钮的处理过程中显示动画gif。

下面,当按下按钮时,它会在列表中搜索字符串&#34; Snow White&#34;并将PictureBox1的Visible属性设置为True。如果你已经添加了一个GIF到PictureBox1(如果你不知道我如何在资源中链接它)你可以看到PictureBox1的加载gif。当循环找到&#34;白雪公主&#34;在moviesList中它会显示&#34;找到它!&#34;在Label1中将PictureBox1的Visible属性设置为False。

示例代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim moviesList As New List(Of String) From {"Cinderella", "Snow White", "Rapunzel"}
    PictureBox1.Visible = True
    For Each movie In moviesList
        If movie = "Snow White" Then
            PictureBox1.Visible = False
            Label1.Text = "Found it!"
        End If
    Next
End Sub

<强>资源:

有关其他信息,您可以使用它们来实现您的目标。

为PictureBox设置动画: https://www.youtube.com/watch?v=Zsvi0p9YUE4

将Gif放入PictureBox: https://www.youtube.com/watch?v=igSsB_61BR8

创建加载屏幕: https://www.youtube.com/watch?v=w8mtv9zJBD0

BackgroundWorker信息: BackgroundWorker Documentation