Solved

VB.NET - Show progressbar while running background query

Posted on 2013-06-18
2
2,723 Views
Last Modified: 2013-06-19
I am using a background worker to perform a pretty intensive stored procedure that takes a little while.  I would like to show a marquee style progress bar while the query is running so the user knows that the application has not hung.

My background worker populates a datagridview so I get a 'Cross-thread operation not valid' error.  I invoked the method in the DoWork sub but the ui of the progress bar form does not get updated... just a ghost outline of the form and then it disappears when the bw completes.  Please let me know what I am doing wrong.

here is a snippet of what i have

Public Class frmMSSViewer
    Private connstring As String = "blah blah"
    Private bw As New BackgroundWorker

    Public Sub New()
        InitializeComponent()
        bw.WorkerSupportsCancellation = True
        AddHandler bw.DoWork, New DoWorkEventHandler(AddressOf bw_DoWork)
        AddHandler bw.RunWorkerCompleted, New RunWorkerCompletedEventHandler(AddressOf bw_RunWorkerCompleted)
    End Sub

    Private Sub MSSViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
        PopulateOpenNames()
        If Not bw.IsBusy Then
            bw.RunWorkerAsync()
        End If
    End Sub

#Region "Background Worker"
    Delegate Sub bw_DoWork_Delegate(ByVal sender As Object, ByVal e As DoWorkEventArgs)

    Private Sub bw_DoWork(sender As Object, e As DoWorkEventArgs)
        Try
            If Me.dgvMSS.InvokeRequired Then
                Dim dlgt As New bw_DoWork_Delegate(AddressOf bw_DoWork)
                Me.Invoke(dlgt, New Object() {[sender], [e]})
            Else
                Dim ds As DataSet = SqlHelper.ExecuteDataset(connstring, "mss.uspLorealMSSResponse_Quarter", Nothing)
                dgvMSS.DataSource = ds.Tables(0).DefaultView
                dgvMSS.AutoResizeColumns()
                dgvMSS.Columns(dgvMSS.Columns.Count - 1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            End If
        Catch ex As Exception
            MessageBox.Show("Error populating datagrid." & vbCrLf & ex.InnerException.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub bw_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
        If e.Error IsNot Nothing Then
            MessageBox.Show(e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
        frmProgress.Close()
    End Sub
#End Region
End Class

Open in new window

0
Comment
Question by:FamousMortimer
2 Comments
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 39257614
This is a common mistake.  what you've done is invoked the ENTIRE bw_DoWork() method which means everything in there is running in  the main UI thread; thus negating the whole point of using a backgroundworker in the first place.

You should let the query run on the background thread and then only invoke what needs to be updated.  A more standard approach is to use the ReportProgress() method and ProgressChanged() event to update the GUI.  In your case, though, I would simply set "e.Result" in the worker and then update everything in the RunWorkerCompleted() event like this:
    Private Sub bw_DoWork(sender As Object, e As DoWorkEventArgs)
        e.Result = SqlHelper.ExecuteDataset(connstring, "mss.uspLorealMSSResponse_Quarter", Nothing)
    End Sub

    Private Sub bw_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
        If e.Error IsNot Nothing Then
            MessageBox.Show("Error populating datagrid." & vbCrLf & e.Error.InnerException.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        ElseIf Not e.Cancelled Then
            dgvMSS.DataSource = e.Result
            dgvMSS.AutoResizeColumns()
            dgvMSS.Columns(dgvMSS.Columns.Count - 1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
        End If
        frmProgress.Close()
    End Sub

Open in new window


Also note that I've removed the Try/Catch in the worker as this allows the exception to be passed to RunWorkerCompleted().
0
 
LVL 10

Author Closing Comment

by:FamousMortimer
ID: 39260256
Very helpful.  Thank You
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Turn on intranet settings 1 55
Run time Error 4 47
VB.NET 2008 Publish Error 2 24
No Data for DropDown List 2 22
Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now