Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

VB.NET - Show progressbar while running background query

Posted on 2013-06-18
2
Medium Priority
?
3,077 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 2000 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…

650 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