Results 1 to 13 of 13

Thread: [RESOLVED] Strungling in BackgroundWorker_DoWork

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2009
    Posts
    135

    Resolved [RESOLVED] Strungling in BackgroundWorker_DoWork

    Hi,
    i have long running process in my BackgroundWorker_DoWork..

    here:
    Code:
    Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    
    'Uploading XML File in remote server here
    
    End Sub
    the problem is i dont have a loop inside my DoWork.i cannot cancelled the worker thread immediately. any idea on this..

    thank you..

  2. #2
    Wall Poster TysonLPrice's Avatar
    Join Date
    Sep 2002
    Location
    Columbus, Ohio
    Posts
    3,969

    Re: Strungling in BackgroundWorker_DoWork

    Here is an example off something I found on the web and tested a while ago:

    Code:
    'From http://vbnotebookfor.net/2007/09/24/how-to-update-controls-using-backgroundworker-in-vbnet/
    Public Class Form1
        Private WithEvents BackGroundWorker As System.ComponentModel.BackgroundWorker
    
        Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
    
            btnStart.Enabled = False
            btnCancel.Enabled = True
            lstValues.Items.Clear()
            prgThread.Value = 0
            BackGroundWorker = New System.ComponentModel.BackgroundWorker
            BackGroundWorker.WorkerReportsProgress = True
            BackGroundWorker.WorkerSupportsCancellation = True
            BackGroundWorker.RunWorkerAsync()
    
    
        End Sub
    
        Private Sub BackGroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackGroundWorker.DoWork
            Dim ListText As String
            For Value As Integer = 0 To 100
                If BackGroundWorker.CancellationPending Then
                    Exit For
                End If
                ListText = String.Concat("Item #", Value)
                BackGroundWorker.ReportProgress(Value, ListText)
                Threading.Thread.Sleep(100)
            Next
        End Sub
    
        Private Sub BackGroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackGroundWorker.ProgressChanged
            prgThread.Value = e.ProgressPercentage
            lstValues.Items.Add(e.UserState)
        End Sub
    
        Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
            BackGroundWorker.CancelAsync()
        End Sub
    
        Private Sub BackGroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackGroundWorker.RunWorkerCompleted
            btnStart.Enabled = True
            btnCancel.Enabled = False
        End Sub
    End Class

  3. #3
    Addicted Member
    Join Date
    Mar 2007
    Posts
    163

    Re: Strungling in BackgroundWorker_DoWork

    jmcilhinney submited a nice example regarding background workers in the vb.net code bank.
    Have a look here for more info it might help you out.

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Aug 2009
    Posts
    135

    Re: Strungling in BackgroundWorker_DoWork

    Quote Originally Posted by stavris View Post
    jmcilhinney submited a nice example regarding background workers in the vb.net code bank.
    Have a look here for more info it might help you out.
    Hello, i already tested the examples posted by jmcilhinney..but i my case..i dont have a loop inside the DoWork...if i also place a loop inside it..i do not know what maximum number in for loop..like 100 as jm example..

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Aug 2009
    Posts
    135

    Re: Strungling in BackgroundWorker_DoWork

    Code:
     Private Sub BackGroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackGroundWorker.DoWork
            Dim ListText As String
            For Value As Integer = 0 To 100'is this number fix?
                If BackGroundWorker.CancellationPending Then
                    Exit For
                End If
                ListText = String.Concat("Item #", Value)
                BackGroundWorker.ReportProgress(Value, ListText)
                Threading.Thread.Sleep(100)
            Next
    is it necessary to put a loop inside a DoWork...?

  6. #6
    Addicted Member
    Join Date
    Mar 2007
    Posts
    163

    Re: Strungling in BackgroundWorker_DoWork

    In the examples provided a repetitive task takes place hence the loops.

    In your case you said
    'Uploading XML File in remote server here

    So I don't think that you need a loop no (I might however missunderstood what you are trying to achieve)
    Essentially the do work part of your background worker will go ahead and do the task in hand on a separate thread...

  7. #7
    PowerPoster Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Bottesford, North Lincolnshire, England.
    Posts
    2,500

    Re: Strungling in BackgroundWorker_DoWork

    Quote Originally Posted by [gja] View Post
    but i my case..i dont have a loop inside the DoWork...if i also place a loop inside it..i do not know what maximum number in for loop..like 100 as jm example..
    You don't need to know in advance how many iterations of the loop are required: -

    Code:
     
        For i As Integer = 1 To 100
            'Raise the ProgressChanged event in the UI thread.
            worker.ReportProgress(i, i & " iterations complete")
     
            'Perform some time-consuming operation here.
            Threading.Thread.Sleep(250)
        Next i
    just becomes: -

    Code:
     
        For i As Integer = 1 To X
     ' where X is the number you require (held in a global variable maybe). 
            'Raise the ProgressChanged event in the UI thread.
            worker.ReportProgress(i, i & " iterations complete")
     
            'Perform some time-consuming operation here.
            Threading.Thread.Sleep(250)
        Next i
    Along with the sunshine there has to be a little rain sometime.

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Strungling in BackgroundWorker_DoWork

    If you're not performing a repetitive task then you don't need a loop. You aren't so you don't.

    You don't need a loop to be able to cancel a background operation. What you do need is to be calling multiple methods in between which you can cancel the operation. If you can't test CancellationPending and set e.Cancel then you can't cancel the operation, plain and simple. If you can then you can.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Aug 2009
    Posts
    135

    Re: Strungling in BackgroundWorker_DoWork

    this is what i have inside the DoWork...

    Code:
    'Export XML
            Dim objCookie As New CookieContainer
            'Dim ls_headerData As String
            Dim objUri As Uri
            Dim objWebRequest As HttpWebRequest
            Dim objWebResponse As HttpWebResponse = Nothing
    
            Dim ls_boundary As String
            Dim sb_builder As StringBuilder
            Dim lbyte_postData() As Byte
            Dim lbyte_boundary() As Byte
    
            'Streams
            Dim objFileStream As FileStream = Nothing
            Dim objRequestStream As Stream = Nothing
            Dim objStreamReader As StreamReader = Nothing
    
            Dim li_length As Long
            Dim li_bytesRead As Integer
            Dim enc As ASCIIEncoding
    
            Dim ls_readData As String
    
            Dim ls_url As String
    
            Try
                'WriteToEventLog("Uploading Started" & ps_filename & ".")
    
                ls_url = ps_url & "/test/exportxml.asp?Src=f0rm&devision=" & ps_dbname
                objUri = New Uri(ls_url)
                objWebRequest = CType(WebRequest.Create(objUri), HttpWebRequest)
                ls_boundary = "--" & Now.ToString
    
                'Initialize request object
                objWebRequest.Credentials = New System.Net.NetworkCredential(ps_lnkUsername, ps_lnkPassword)
                objWebRequest.UserAgent = "ASI"
                objWebRequest.ContentType = "multipart/form-data; boundary=" & ls_boundary
                objWebRequest.Method = "POST"
                objWebRequest.KeepAlive = True
                objWebRequest.CookieContainer = objCookie
                objWebRequest.Timeout = 3600000  'added last 8/17/2010 by ryan
              
                'Build the post header data
                sb_builder = New StringBuilder
    
                sb_builder.Append("--")
                sb_builder.Append(ls_boundary)
                sb_builder.Append(vbCrLf)
                sb_builder.Append("Content-Disposition: form-data; name=""")
                sb_builder.Append("XMLFile")
                sb_builder.Append("""; filename=""")
                sb_builder.Append(Path.GetFileName(ps_filename))
                sb_builder.Append("""")
                sb_builder.Append(vbCrLf)
                sb_builder.Append("Content-Type: ")
                sb_builder.Append("text/xml")
                sb_builder.Append(vbCrLf)
                sb_builder.Append(vbCrLf)
    
                lbyte_postData = System.Text.Encoding.UTF8.GetBytes(sb_builder.ToString())
                lbyte_boundary = Encoding.ASCII.GetBytes(vbCrLf & "--" + ls_boundary + vbCrLf)
    
                objFileStream = New FileStream(ps_filename, FileMode.Open, FileAccess.Read)
                li_length = lbyte_postData.Length + objFileStream.Length + lbyte_boundary.Length
                objWebRequest.ContentLength = li_length
    
                objRequestStream = objWebRequest.GetRequestStream()
                ' write the data to be posted to the Request Stream
                objRequestStream.Write(lbyte_postData, 0, lbyte_postData.Length)
    
                Dim lbyte_buffer(Math.Min(4096, CInt(objFileStream.Length))) As Byte
                enc = New ASCIIEncoding
                li_bytesRead = objFileStream.Read(lbyte_buffer, 0, lbyte_buffer.Length)
    
                While li_bytesRead <> 0
                    objRequestStream.Write(lbyte_buffer, 0, li_bytesRead)
                    li_bytesRead = objFileStream.Read(lbyte_buffer, 0, lbyte_buffer.Length)
                End While
    
                objRequestStream.Write(lbyte_boundary, 0, lbyte_boundary.Length)
    
                'Get the response
                objWebResponse = CType(objWebRequest.GetResponse(), HttpWebResponse)
                objStreamReader = New StreamReader(objWebResponse.GetResponseStream(), Encoding.Default)
    
                ls_readData = objStreamReader.ReadToEnd()
    
                'Transactions
                If ParseHTMLResult(ls_readData) <> 0 Then
                    Throw New Exception("Some errors found while uploading XML document.")
                End If
    
                'XMLUpload = 1
                'WriteToEventLog("Done Uploading " & ps_filename & "!")
    
            Catch ex As WebException
                'error was related to web connection
                ''WriteToEventLog("ERROR: " & ex.Message)
                'XMLUpload = 2
            Catch ex As Exception
                'XMLUpload = 0
                'WriteToEventLog("ERROR: " & ex.Message)
            Finally
                'Housekeeping
                If Not objFileStream Is Nothing Then
                    objFileStream.Close()
                End If
                If Not objRequestStream Is Nothing Then
                    objRequestStream.Close()
                End If
                If Not objStreamReader Is Nothing Then
                    objStreamReader.Close()
                End If
                If Not objWebResponse Is Nothing Then
                    objWebResponse.Close()
                End If
            End Try
    is there any other way to forcely terminate the operation?(e.g large xml file upload)and a user decided to terminate it by clicking cancel button..if the system don't react to it..they might think that the cancel button was not working..

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Strungling in BackgroundWorker_DoWork

    Like I said, the only way that you can cancel the operation is if you can test CancellationPending and set Cancel. You can do that in between any two lines of code insde the DoWork event handler. You can't do it "during" a line of code. If you call a method that runs for 10 minutes inside the DoWork event handler then you can terminate the operation before that method or after but not during. If you are providing the user a means to cancel and you have to wait for a while to actually cancel the operation in the DoWork event handler then it's up to you to design the app such that the IS aware that their cancellation has been registered but not implemented yet. You might do that by disabling the Cancel button and displaying a message somewhere (on the button, in a status bar, etc) to informs the user of exactly that. The user knows what you tell them.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    Aug 2009
    Posts
    135

    Re: Strungling in BackgroundWorker_DoWork

    Quote Originally Posted by jmcilhinney View Post
    You can do that in between any two lines of code insde the DoWork event handler. You can't do it "during" a line of code.
    pardon me,a little confused on this?


    as what u have all said..i convince that in my case im not gonna able to terminate the operation while it start uploading xml file.bcoz if it reach this code.this is the lines of code that takes time to process.bcoz it waiting for the response of a webservice..

    Code:
     'Get the response
                objWebResponse = CType(objWebRequest.GetResponse(), HttpWebResponse)
                objStreamReader = New StreamReader(objWebResponse.GetResponseStream(), Encoding.Default)
    if i still provide cancellation of operation it is still no use..bcoz if the upload method starts there is no way to terminate it.unless it reach to the end..

  12. #12
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Strungling in BackgroundWorker_DoWork

    You can provide the ability to cancel before calling GetResponse, after calling GetResponse and before calling GetResponseStream, and after calling GetResponseStream:
    Code:
                'You can cancel here
                objWebResponse = CType(objWebRequest.GetResponse(), HttpWebResponse)
                'You can cancel here
                objStreamReader = New StreamReader(objWebResponse.GetResponseStream(), Encoding.Default)
                'You can cancel here
    I'm not 100&#37; sure but I believe that the actual data doesn't get downloaded from the server until you read it from the stream. In that case you can cancel during the actual download if the download is broken up. Once you've got the StreamReader, you can also then read the data in chunks rather than in one block. That will allow you to cancel between chunks as well.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Aug 2009
    Posts
    135

    Re: Strungling in BackgroundWorker_DoWork

    You got it jm!...Thank you very much!...

    Thank you also to people who reply my post...:-)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width