BackgroundWorker在需要时未运行 [英] BackgroundWorker not Running when it's needed

查看:241
本文介绍了BackgroundWorker在需要时未运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,使用户可以上传一个大文件,将其与之前上传的另一个大文件进行比较,并返回新条目和不连续条目的列表.

这需要程序运行一些查询,因此程序需要一段时间才能完成任务.

当然,这意味着在程序完成任务之前,用户无法执行其他任何操作.为了防止这种情况发生,我在项目中添加了BackgroundWorker.

问题是BackgroundWorker无法启动,给了我同样的问题.

您能帮我解决这个问题吗?谢谢!

代码:

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim opendialog As New OpenFileDialog
    Dim filepath As String = ""
    Dim cellvalue(20) As String

    opendialog.Title = "Elija el archivo que quiere importar"
    opendialog.Filter = "CSV (*.csv)|*.csv"

    If opendialog.ShowDialog() = DialogResult.Cancel Then
        Exit Sub
    End If

    filepath = Replace(opendialog.FileName, "\", "\\")

    Label1.Visible = True 'This is supposed to appear first, but it doesn't appear until the end of the method.

    'Reading CSV file content 
    Cmd.CommandText = "SELECT COUNT(*) AS cuenta FROM libros WHERE 1"
    rs = Cmd.Execute

    If rs("cuenta").Value = 0 Then
        BackgroundWorker1.RunWorkerAsync()
        'MySQL queries, some of which takes a long time due to the large file being processed

        Beep()
        MsgBox("Archivo exportado con éxito",, "Exito")
        BackgroundWorker1.CancelAsync()

    Else
        BackgroundWorker1.RunWorkerAsync()

        'MySQL queries, some of which takes a long time due to the large file being processed

        Beep()
        MsgBox("Archivo exportado con éxito",, "Exito")
        BackgroundWorker1.CancelAsync()

    End If
End Sub

Private Sub BackgroundWoker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    ' Update the progress bar
    Me.ProgressBar1.Value = e.ProgressPercentage
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    If e.Cancelled Then
        Label1.Text = "Cancelled"
    Else
        Label2.Text = "Completed"
    End If
End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object,
                 ByVal e As System.ComponentModel.DoWorkEventArgs) _
                 Handles BackgroundWorker1.DoWork
    ' Do some time-consuming work on this thread.
    System.Threading.Thread.Sleep(5)
End Sub
 

顾名思义,

解决方案

RunWorkerAsync是一个异步方法调用.这意味着这里唯一要做的工作就是启动DoWork事件处理程序并立即返回.因此,您的代码现在有两条执行路径,一条在DoWork事件处理程序中(刚刚开始工作,可能什么也没做),另一条是调用RunWorkerAsync之后的代码(ButtonClick中的代码).

最后一个代码显示一个消息框,然后调用CancelAsync,您可以想象此调用对您的DoWork执行线程的作用.

因此,您只需要在显示任何内容之前等待即可,而Completed事件正是您用来等待DoWork事件处理程序完成所需要的

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
.....
    BackgroundWorker1.RunWorkerAsync()
    ' Remove these lines....
    ' Beep()
    ' MsgBox("Archivo exportado con éxito",, "Exito")
    ' BackgroundWorker1.CancelAsync()
End Sub

 Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    If e.Cancelled Then
        Label1.Text = "Cancelled"
    Else
        Label2.Text = "Completed"
        ' Add the message here....'
        Beep()
        MsgBox("Archivo exportado con éxito",, "Exito")

        ' Of course at this point you don't need to cancel anything....'
    End If
End Sub

Private Sub BackgroundWoker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    Me.ProgressBar1.Value = e.ProgressPercentage
End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object,
             ByVal e As System.ComponentModel.DoWorkEventArgs) _
             Handles BackgroundWorker1.DoWork
    ' Now suppose that your work here could be divided in 5 methods'

    ExecuteMethod1()
    backgroundWorker1.ReportProgress(20)   
    ExecuteMethod2)
    backgroundWorker1.ReportProgress(40   
    ExecuteMethod3
    backgroundWorker1.ReportProgress(60)   
    ExecuteMethod4
    backgroundWorker1.ReportProgress(80)   
    ExecuteMethod5
    backgroundWorker1.ReportProgress(100)   

End Sub
 

I am writing a program which lets users upload a large file, compare it to another large file uploaded before and return a list of new entries and discontinued entries.

This requires the program to run a few queries, so it takes a while for the program to complete the task.

Of course, this means that until the program is done with the task, the user cannot do anything else. To prevent that from happening I have included a BackgroundWorker to the project.

The problem is, the BackgroundWorker doesn't start, giving me the same problem.

Can you please help me with this problem? Thanks!

Code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim opendialog As New OpenFileDialog
    Dim filepath As String = ""
    Dim cellvalue(20) As String

    opendialog.Title = "Elija el archivo que quiere importar"
    opendialog.Filter = "CSV (*.csv)|*.csv"

    If opendialog.ShowDialog() = DialogResult.Cancel Then
        Exit Sub
    End If

    filepath = Replace(opendialog.FileName, "\", "\\")

    Label1.Visible = True 'This is supposed to appear first, but it doesn't appear until the end of the method.

    'Reading CSV file content 
    Cmd.CommandText = "SELECT COUNT(*) AS cuenta FROM libros WHERE 1"
    rs = Cmd.Execute

    If rs("cuenta").Value = 0 Then
        BackgroundWorker1.RunWorkerAsync()
        'MySQL queries, some of which takes a long time due to the large file being processed

        Beep()
        MsgBox("Archivo exportado con éxito",, "Exito")
        BackgroundWorker1.CancelAsync()

    Else
        BackgroundWorker1.RunWorkerAsync()

        'MySQL queries, some of which takes a long time due to the large file being processed

        Beep()
        MsgBox("Archivo exportado con éxito",, "Exito")
        BackgroundWorker1.CancelAsync()

    End If
End Sub

Private Sub BackgroundWoker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    ' Update the progress bar
    Me.ProgressBar1.Value = e.ProgressPercentage
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    If e.Cancelled Then
        Label1.Text = "Cancelled"
    Else
        Label2.Text = "Completed"
    End If
End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object,
                 ByVal e As System.ComponentModel.DoWorkEventArgs) _
                 Handles BackgroundWorker1.DoWork
    ' Do some time-consuming work on this thread.
    System.Threading.Thread.Sleep(5)
End Sub

解决方案

RunWorkerAsync is, as the name implies, an async method call. This means that the only work done here is to start the DoWork event handler and return immediately. Thus your code now has two paths of execution, the one in the DoWork event handler (that has just started its work and it has probably done nothing) and the code that follows the call to RunWorkerAsync (the code in the ButtonClick).

This last code shows a messagebox and then call CancelAsync, and you could imagine what this call do to your DoWork thread of execution.

So you just need to wait before displaying anything and the Completed event is exactly what you need to use to wait the completition of your DoWork event handler

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
.....
    BackgroundWorker1.RunWorkerAsync()
    ' Remove these lines....
    ' Beep()
    ' MsgBox("Archivo exportado con éxito",, "Exito")
    ' BackgroundWorker1.CancelAsync()
End Sub

 Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    If e.Cancelled Then
        Label1.Text = "Cancelled"
    Else
        Label2.Text = "Completed"
        ' Add the message here....'
        Beep()
        MsgBox("Archivo exportado con éxito",, "Exito")

        ' Of course at this point you don't need to cancel anything....'
    End If
End Sub

Private Sub BackgroundWoker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    Me.ProgressBar1.Value = e.ProgressPercentage
End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object,
             ByVal e As System.ComponentModel.DoWorkEventArgs) _
             Handles BackgroundWorker1.DoWork
    ' Now suppose that your work here could be divided in 5 methods'

    ExecuteMethod1()
    backgroundWorker1.ReportProgress(20)   
    ExecuteMethod2)
    backgroundWorker1.ReportProgress(40   
    ExecuteMethod3
    backgroundWorker1.ReportProgress(60)   
    ExecuteMethod4
    backgroundWorker1.ReportProgress(80)   
    ExecuteMethod5
    backgroundWorker1.ReportProgress(100)   

End Sub

这篇关于BackgroundWorker在需要时未运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆