Results 1 to 35 of 35

Thread: [RESOLVED] Help with cancelling background worker?

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Resolved [RESOLVED] Help with cancelling background worker?

    Hello,

    I have some background workers in my application and I'm having trouble trying to cancel them, so far I have the following...

    Code:
    If Backgroundworker1.IsBusy Then
                Backgroundworker1.CancelAsync()
                Backgroundworker1 = Nothing
            End If
    
    If Backgroundworker2.IsBusy Then
                Backgroundworker2.CancelAsync()
                Backgroundworker2 = Nothing
            End If
    
    If Backgroundworker3.IsBusy Then
                Backgroundworker3.CancelAsync()
                Backgroundworker3 = Nothing
            End If
    Is there a way to kill all background workers in one go? Also, I have noticed that sometimes when I kill the background worker it still completes.

    Would you recommend .dispose?

    Many thanks.
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  2. #2
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    351

    Re: Help with cancelling background worker?

    http://msdn.microsoft.com/en-us/libr...(v=vs.95).aspx

    Is a good example of how to cancel a background worker
    Rico

    Using: VB.net & MS SQL

  3. #3
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    The CancelAsync method just sets a flag in the BackgroundWorker to inform it that the task needs to be cancelled. You would need to check for CancellationPending inside the procedure the BackgroundWorker is running, and cancel out accordingly. If you don't do, it will continue to run normally.

    Are you sure you are doing everything correctly?
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  4. #4
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    To answer the first part of your question: How to cancel all the BackgroundWorkers,

    You can do it like this:
    vb.net Code:
    1. '' Declare an array of BackgroundWorkers
    2. Dim MyBackgroundWorkers() As BackgroundWorker
    3.  
    4. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    5.     '' add all your BackgroundWorkers to the array
    6.     MyBackgroundWorkers = New BackgroundWorker() {BackgroundWorker1, BackgroundWorker2, BackgroundWorker3, BackgroundWorker4, BackgroundWorker5}
    7. End Sub
    8.  
    9. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    10.     '' now you can Cancel all of them in a loop
    11.     For Each bgw In MyBackgroundWorkers
    12.         If bgw.IsBusy Then
    13.             bgw.CancelAsync()
    14.         End If
    15.     Next
    16. End Sub
    This is assuming that your BackgroundWorkers are controls you added from the toolbox at design time. If it was declared and added from code, you would need to make appropriate modifications in the Form_Load code.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: Help with cancelling background worker?

    Calling CancelAsync doesn't cancel a BackgroundWorker's task. It simply requests that the task be cancelled. It's up to you to write code in the DoWork event handler to detect that request and duly end the task. For several examples of using the BackgroundWorker, including cancellation, follow the CodeBank link in my signature and check out my post on Using The BackgroundWorker.

  6. #6

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    Many thanks guys for your help. Jmcilhinney, the codebank was very helpful and I have figured out how to do the cancel using your example.

    I have decided to take your advice and not bother with many background workers and do the coding within the one BG, What I was trying to do was when the user clicks cancel then I wanted to kill the background worker, move the folder to another location and delete the folder but it looks like something has hold of a process in one of the files in the folders so I cant kill it.

    Do you know if there is anything I could use to kill a folder and any process that might be in use in that folder? I use the IO delete directory.

    Code:
        If My.Computer.FileSystem.DirectoryExists(“Path”) = True Then
                My.Computer.FileSystem.DeleteDirectory“Path”), FileIO.DeleteDirectoryOption.DeleteAllContents)
            End If
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  7. #7
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    While cancelling out from a BackgroundWorker, ensure that you close your resources properly. Probably you had a file open which you didn't close when you cancelled out of the BackgroundWorker.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

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

    Re: Help with cancelling background worker?

    Pradeep is quite correct. It's for this reason that you should use a Using block to create short-lived disposable objects, e.g. a FileStream or StreamReader. That way, the object is disposed when you leave the Using block, no matter how you leave it. Disposing an object that opens a file will close the file.

  9. #9
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    You can have a look at this thread to get an overview of how a BackgroundWorker should be properly coded:

    http://www.vbforums.com/showthread.php?t=680130
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

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

    Re: Help with cancelling background worker?

    You didn't like my CodeBank examples Pradeep?

  11. #11

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    Thanks Pradeep & JM.


    I have pasted the coding that goes in my background worker, its pretty simple really just some process commands and some coding to filter the data.


    Code:
    ‘The following coding is in my Backgroundworker Do Work
    
     myProcess = New Process
    
      Me.label1.Text = "Run first command"
    
    
            Dim sid As String
    	‘ Start My process coding
            Dim sidIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sidOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sidErr As System.IO.StreamReader = myProcess.StandardError
    
            sidIn.AutoFlush = True
    
            sidIn.Write("Run First Command" & System.Environment.NewLine)
            sidIn.Write("exit" & System.Environment.NewLine)
    
            sid = sidOut.ReadToEnd()
    
            sidIn.Close()
            sidOut.Close()
            sidErr.Close()
            myProcess.Close()
    
      Me.label1.Text = "Edit the data"
    
            
            Dim sourcefile As String = IO.Path.Combine("Path")
            Dim rdrfile As IO.StreamReader = IO.File.OpenText(sourcefile)
            Dim strtemp() As String
            Dim FileLines As New List(Of String)
            Do While rdrfile.Peek <> -1
                FileLines.Add(rdrfile.ReadLine)
            Loop
            rdrfile.Close()
    
            Dim writer As IO.StreamWriter = New IO.StreamWriter(sourcefile, False)
            Dim Columns As New List(Of String)
    
            For Each Str As String In FileLines
                strtemp = Str.Split(" "c)
                If Trim(strtemp(0)) = "FILENO" Then writer.Write(strtemp(11).Trim & vbCrLf)
            Next
    
            For Each filtereditem As String In Columns
                writer.Write(filtereditem & vbCrLf)
            Next
    
            writer.Close()
            FileLines.Clear()
    
            Me.label1.Text = "Run second command"
    
          
            myProcess = New Process
          ‘ Start My process coding
            Dim smed As String
           
    
            Dim smedIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim smedOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim smedErr As System.IO.StreamReader = myProcess.StandardError
    
            smedIn.AutoFlush = True
            smedIn.Write("Run Second Command" & System.Environment.NewLine)
            smedIn.Write("exit" & System.Environment.NewLine)
    
            smed = smedOut.ReadToEnd()
    
            smedIn.Close()
            smedOut.Close()
            smedErr.Close()
            myProcess.Close()
    
            Me.label1.Text = "Run Third Command"
    
            myProcess = New Process
    
            Dim sfre As String
          ‘ Start My process coding
            Dim sfreIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sfreOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sfreErr As System.IO.StreamReader = myProcess.StandardError
    
            sfreIn.AutoFlush = True
            sfreIn.Write("Run Third Command” & System.Environment.NewLine)
            sfreIn.Write("exit" & System.Environment.NewLine)
    
            sfre = sfreOut.ReadToEnd()
    
            sfreIn.Close()
            sfreOut.Close()
            sfreErr.Close()
            myProcess.Close()
    
            Me.label1.Text = "Run Fourth Command"
    
            myProcess = New Process
    
            Dim scl As String
    
            Dim sclIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sclOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sclErr As System.IO.StreamReader = myProcess.StandardError
    
            sclIn.AutoFlush = True
            sclIn.Write("Run Fourth Command" & System.Environment.NewLine)
            sclIn.Write("exit" & System.Environment.NewLine)
    
            scl = sclOut.ReadToEnd()
    
            sclIn.Close()
            sclOut.Close()
            sclErr.Close()
            myProcess.Close()
    
            Me.label1.Text = "Edit the Data"
    
            Dim Open As String = IO.Path.Combine("Path")
            Dim Save As String = IO.Path.Combine("Path")
    
            Dim sb As New System.Text.StringBuilder
    
            Dim Lines =
                (From line In IO.File.ReadAllLines(Open)
                    Where line.Length > 0
    Select line).ToList
    
            For Each item In Lines
                Dim TempItem = item
                Dim Column1 = TempItem.Substring(0, TempItem.IndexOf(" "))
                TempItem = TempItem.Replace(Column1, "").Trim
                Dim Column2 = TempItem.Substring(0, 20)
    
                TempItem = TempItem.Replace(Column2, "").Trim
    
                Dim Parts = System.Text.RegularExpressions.Regex.Replace(TempItem.TrimStart, " {2,}", ",").Replace(" ", ",").Split(","c)
    
                sb.AppendLine(
                    String.Format("{0}{1}",
                                  Column1.PadRight(100, " "c),
                                  Column2.PadRight(100, " "c),))
    
            Next
    
            IO.File.WriteAllText(Save, sb.ToString)
    
            Dim inputFile = Regex.Replace(IO.File.ReadAllText(Save), "[ ]{2,}", " ")
            IO.File.WriteAllText(Save, inputFile)
    
    
         Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
    
    
            If worker.CancellationPending Then
                e.Cancel = True
    
       sidIn.Close()
            sidOut.Close()
            sidErr.Close()
            myProcess.Close()
    
            writer.Close()
            FileLines.Clear()
    
    
    .        smedIn.Close()
            smedOut.Close()
            smedErr.Close()
            myProcess.Close()
    
            sfreIn.Close()
            sfreOut.Close()
            sfreErr.Close()
            myProcess.Close()
    
    
            sclIn.Close()
            sclOut.Close()
            sclErr.Close()
            myProcess.Close()
    
    IO.File.WriteAllText(Save, sb.ToString)
    
    
            End If
    As you can see I’ve tried to close all connections when cancellation pending.
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  12. #12

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    Code:
       myProcess.StartInfo.FileName = "c:\windows\system32\cmd.exe"
            myProcess.StartInfo.UseShellExecute = False
            myProcess.StartInfo.CreateNoWindow = True
            myProcess.StartInfo.RedirectStandardInput = True
            myProcess.StartInfo.RedirectStandardOutput = True
            myProcess.StartInfo.RedirectStandardError = True
            myProcess.Start()
    Thats how i start my process
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  13. #13
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    Quote Originally Posted by jmcilhinney View Post
    You didn't like my CodeBank examples Pradeep?
    oooohhh
    My bad! I completely forgot about that one when I was posting my sample.

    It looks like that's far better than my sample and also has many examples in the followup posts

    @frankwhite: Here's the link:
    http://www.vbforums.com/showthread.php?t=471889
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  14. #14
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    The problem is:
    You have used the worker.CancellationPending in just the opposite way of how it should be used.
    Currently, you have your code to release the resources (close method calls) inside the If worker.CancellationPending Then ... End If block. This means that your resources will be closed only if you cancel and not otherwise.

    And your BackgroundWorker will never effectively cancel the Work because you never checked for CancellationPending in the rest of the code.

    Do the following things:
    1. Move the code to close your resources outside the IF..END IF block.
    2. Earlier in the code, check for CancellationPending and cut short your Work accordingly. Loops are usually the best places to do this.
    Those code blocks (inside the loops) would look something like this:
    Code:
    If worker.CancellationPending Then
        e.Cancel = True
        Exit Do     ' or Exit For etc. as the case may be.
    End If
    Post back here if you still face problems.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  15. #15

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    I think I understand, do you mean have the following coding in each section of the background worker?

    Code:
        If worker.CancellationPending Then
                e.Cancel = True
            End If
    When you say Loops, do you mean in each section of the coding?
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  16. #16
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: Help with cancelling background worker?

    Basically you need to break up the work in your event handler into logical tasks. If you're using a loop, as many examples do, then each iteration of the loop is a task. You need to test CancellationPending between each pair of tasks and, if it's True, don't perform any further tasks. As suggested, cleanup must be performed whether the background work is cancelled or not. If each "section" you're talking about is a logical task then yes, you must check for cancellation after each section. You must also NOT execute any more sections.

  17. #17
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    Quote Originally Posted by frankwhite View Post
    I think I understand, do you mean have the following coding in each section of the background worker?

    Code:
        If worker.CancellationPending Then
                e.Cancel = True
            End If
    When you say Loops, do you mean in each section of the coding?
    Checking for once in each loop would do.
    Don't forget to put the the Exit Do / Exit For etc. Without that it would be worthless.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  18. #18

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    Pradeep,

    Do you mean something like the following?

    Code:
             
            Dim intCount As Integer = 0
    
           
            Do While intCount < 1
    
        myProcess = New Process
    
            Dim sid As String
            myProcess.StartInfo.FileName = "c:\windows\system32\cmd.exe"
            myProcess.StartInfo.UseShellExecute = False
            myProcess.StartInfo.CreateNoWindow = True
            myProcess.StartInfo.RedirectStandardInput = True
            myProcess.StartInfo.RedirectStandardOutput = True
            myProcess.StartInfo.RedirectStandardError = True
            myProcess.Start()
    
            Dim sidIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sidOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sidErr As System.IO.StreamReader = myProcess.StandardError
    
            sidIn.AutoFlush = True
    
            sidIn.Write("Run first command" & lbljobid.Text & "ImageID.txt" & System.Environment.NewLine)
            sidIn.Write("exit" & System.Environment.NewLine)
    
            sid = sidOut.ReadToEnd()
    
            sidIn.Close()
            sidOut.Close()
            sidErr.Close()
            myProcess.Close()
    
    
    
                'Increment intCount by 1
                intCount += 1
    
    If worker.CancellationPending Then
        e.Cancel = True
        Exit Do    
    End If
    
                End If
    Edit* and so on and so on for the other sections?
    Last edited by frankwhite; May 22nd, 2012 at 06:46 AM.
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  19. #19
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    Quote Originally Posted by frankwhite View Post
    Pradeep,

    Do you mean something like the following?

    Edit* and so on and so on for the other sections?
    Yes you did it right

    Just repeat it for all the other loops.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  20. #20
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    Have a look at this:
    vb.net Code:
    1. Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    2.     '' move this to the start of your DoWork event procedure
    3.     Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
    4.  
    5.     '' your other code
    6.  
    7.     Do While rdrfile.Peek <> -1
    8.         '' your other code
    9.  
    10.         If worker.CancellationPending Then Exit Do
    11.     Loop
    12.  
    13.     '' your other code
    14.  
    15.     For Each Str As String In FileLines
    16.         '' your other code
    17.  
    18.         If worker.CancellationPending Then Exit For
    19.     Next
    20.  
    21.     For Each filtereditem As String In Columns
    22.         '' your other code
    23.  
    24.         If worker.CancellationPending Then Exit For
    25.     Next
    26.  
    27.     '' your other code
    28.  
    29.     For Each item In Lines
    30.         '' your other code
    31.  
    32.         If worker.CancellationPending Then Exit For
    33.     Next
    34.  
    35.     '' your other code
    36.  
    37.  
    38.     '' just before End Sub
    39.     If worker.CancellationPending Then e.Cancel = True
    40. End Sub
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  21. #21

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    thanks,

    when you say ''your other code do you mean still include loops for the other code?

    One more question I have is i forgot to add the 'loop' to the previous code, is something like the following correct?

    Code:
         Dim intCount As Integer = 0
    
    
            Do While intCount < 1
    
    
            Loop
    
            myProcess = New Process
    ''....then the rest of the coding
    
      If worker.CancellationPending Then
                e.Cancel = True
                Exit Do
            End If
    But I get Error 2 'Exit Do' can only appear inside a 'Do' statement.
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  22. #22
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: Help with cancelling background worker?

    Quote Originally Posted by Pradeep1210 View Post
    Have a look at this:
    vb.net Code:
    1. Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    2.     '' move this to the start of your DoWork event procedure
    3.     Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
    4.  
    5.     '' your other code
    6.  
    7.     Do While rdrfile.Peek <> -1
    8.         '' your other code
    9.  
    10.         If worker.CancellationPending Then Exit Do
    11.     Loop
    12.  
    13.     '' your other code
    14.  
    15.     For Each Str As String In FileLines
    16.         '' your other code
    17.  
    18.         If worker.CancellationPending Then Exit For
    19.     Next
    20.  
    21.     For Each filtereditem As String In Columns
    22.         '' your other code
    23.  
    24.         If worker.CancellationPending Then Exit For
    25.     Next
    26.  
    27.     '' your other code
    28.  
    29.     For Each item In Lines
    30.         '' your other code
    31.  
    32.         If worker.CancellationPending Then Exit For
    33.     Next
    34.  
    35.     '' your other code
    36.  
    37.  
    38.     '' just before End Sub
    39.     If worker.CancellationPending Then e.Cancel = True
    40. End Sub
    That's not quite right because that is still going to do the work in the first iteration of every loop even if the work is cancelled right at the start. As I said, if you detect a cancellation request then you need to make sure that you don't do any more work.

  23. #23

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    Thanks Jmcilhinney, is there a suggestion you could make on the best way to do this?

    so If cancellationpending = True then dont run any more coding for the background worker do work event?
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  24. #24
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: Help with cancelling background worker?

    How about the obvious:
    vb Code:
    1. If Not e.CancellationPending Then
    2.     'Do the work here.
    3. End If

  25. #25
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    Quote Originally Posted by jmcilhinney View Post
    That's not quite right because that is still going to do the work in the first iteration of every loop even if the work is cancelled right at the start. As I said, if you detect a cancellation request then you need to make sure that you don't do any more work.
    hmm.. yes

    So it goes like this:
    Code:
    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        '' move this to the start of your DoWork event procedure
        Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
     
        '' your other code
     
        Do While rdrfile.Peek <> -1
            If worker.CancellationPending Then Exit Do
    
            '' your other code
        Loop
     
        '' your other code
     
        For Each Str As String In FileLines
            If worker.CancellationPending Then Exit For
    
            '' your other code
     
        Next
     
        For Each filtereditem As String In Columns
            If worker.CancellationPending Then Exit For
    
            '' your other code
     
        Next
     
        '' your other code
     
        For Each item In Lines
            If worker.CancellationPending Then Exit For
    
            '' your other code
     
        Next
     
        '' your other code
     
     
        '' just before End Sub
        If worker.CancellationPending Then e.Cancel = True
    End Sub
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  26. #26

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    Hi Pradeep,

    so something like so?

    Code:
     Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
    
            Dim intCount As Integer = 0
    
            Do While intCount < 1
    
            Loop
    
            myProcess = New Process
    
            Me.Label1.Text = "Run first command"
    
    
            Dim sid As String
            ' Start My process coding
            Dim sidIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sidOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sidErr As System.IO.StreamReader = myProcess.StandardError
    
            sidIn.AutoFlush = True
    
            sidIn.Write("Run First Command" & System.Environment.NewLine)
            sidIn.Write("exit" & System.Environment.NewLine)
    
            sid = sidOut.ReadToEnd()
    
            sidIn.Close()
            sidOut.Close()
            sidErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    
    
    
            Me.Label1.Text = "Edit the data"
    
    
            Dim sourcefile As String = IO.Path.Combine("Path")
            Dim rdrfile As IO.StreamReader = IO.File.OpenText(sourcefile)
            Dim strtemp() As String
            Dim FileLines As New List(Of String)
    
    
            Do While rdrfile.Peek <> -1
                If worker.CancellationPending Then Exit Do
    
                FileLines.Add(rdrfile.ReadLine)
            Loop
    
            rdrfile.Close()
    
            Dim writer As IO.StreamWriter = New IO.StreamWriter(sourcefile, False)
            Dim Columns As New List(Of String)
    
    
            For Each Str As String In FileLines
                If worker.CancellationPending Then Exit For
    
                strtemp = Str.Split(" "c)
                If Trim(strtemp(0)) = "FILENO" Then writer.Write(strtemp(11).Trim & vbCrLf)
            Next
    
            For Each filtereditem As String In Columns
                If worker.CancellationPending Then Exit For
                writer.Write(filtereditem & vbCrLf)
    
            Next
    
            writer.Close()
            FileLines.Clear()
    
            Do While intCount < 1
    
            Loop
    
            myProcess = New Process
            ' Start My process coding
            Dim smed As String
    
    
            Dim smedIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim smedOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim smedErr As System.IO.StreamReader = myProcess.StandardError
    
            smedIn.AutoFlush = True
            smedIn.Write("Run Second Command" & System.Environment.NewLine)
            smedIn.Write("exit" & System.Environment.NewLine)
    
            smed = smedOut.ReadToEnd()
    
            smedIn.Close()
            smedOut.Close()
            smedErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    
            Do While intCount < 1
    
            Loop
    
            Me.Label1.Text = "Run Third Command"
    
            myProcess = New Process
    
            Dim sfre As String
            ' Start My process coding
            Dim sfreIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sfreOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sfreErr As System.IO.StreamReader = myProcess.StandardError
    
            sfreIn.AutoFlush = True
            sfreIn.Write("Run Third Command" & System.Environment.NewLine)
            sfreIn.Write("exit" & System.Environment.NewLine)
    
            sfre = sfreOut.ReadToEnd()
    
            sfreIn.Close()
            sfreOut.Close()
            sfreErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    
            Do While intCount < 1
    
            Loop
    
            Me.Label1.Text = "Run Fourth Command"
    
            myProcess = New Process
    
            Dim scl As String
    
            Dim sclIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sclOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sclErr As System.IO.StreamReader = myProcess.StandardError
    
            sclIn.AutoFlush = True
            sclIn.Write("Run Fourth Command" & System.Environment.NewLine)
            sclIn.Write("exit" & System.Environment.NewLine)
    
            scl = sclOut.ReadToEnd()
    
            sclIn.Close()
            sclOut.Close()
            sclErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    
            Me.Label1.Text = "Edit the Data"
    
            Dim Open As String = IO.Path.Combine("Path")
            Dim Save As String = IO.Path.Combine("Path")
    
            Dim sb As New System.Text.StringBuilder
    
            Dim Lines =
                (From line In IO.File.ReadAllLines(Open)
                    Where line.Length > 0
            Select line).ToList
    
    
            For Each item In Lines
                If worker.CancellationPending Then Exit For
    
                Dim TempItem = item
                Dim Column1 = TempItem.Substring(0, TempItem.IndexOf(" "))
                TempItem = TempItem.Replace(Column1, "").Trim
                Dim Column2 = TempItem.Substring(0, 20)
    
                TempItem = TempItem.Replace(Column2, "").Trim
    
                Dim Parts = System.Text.RegularExpressions.Regex.Replace(TempItem.TrimStart, " {2,}", ",").Replace(" ", ",").Split(","c)
    
                sb.AppendLine(
                    String.Format("{0}{1}",
                                  Column1.PadRight(100, " "c),
                                  Column2.PadRight(100, " "c), ))
    
    
            Next
    
            IO.File.WriteAllText(Save, sb.ToString)
    
            Dim inputFile = Regex.Replace(IO.File.ReadAllText(Save), "[ ]{2,}", " ")
            IO.File.WriteAllText(Save, inputFile)
    
    
            If worker.CancellationPending Then e.Cancel = True
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  27. #27
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    It looks like you have introduced a few extra infinite looks while making the code changes. Have a look at the highlighted code below.

    I was expecting your rest of the code to remain same except for those single line codes here and there I showed you in the previous post.

    Code:
     Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
    
            Dim intCount As Integer = 0
    
            Do While intCount < 1
    
            Loop
    
            myProcess = New Process
    
            Me.Label1.Text = "Run first command"
    
    
            Dim sid As String
            ' Start My process coding
            Dim sidIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sidOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sidErr As System.IO.StreamReader = myProcess.StandardError
    
            sidIn.AutoFlush = True
    
            sidIn.Write("Run First Command" & System.Environment.NewLine)
            sidIn.Write("exit" & System.Environment.NewLine)
    
            sid = sidOut.ReadToEnd()
    
            sidIn.Close()
            sidOut.Close()
            sidErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    
    
    
            Me.Label1.Text = "Edit the data"
    
    
            Dim sourcefile As String = IO.Path.Combine("Path")
            Dim rdrfile As IO.StreamReader = IO.File.OpenText(sourcefile)
            Dim strtemp() As String
            Dim FileLines As New List(Of String)
    
    
            Do While rdrfile.Peek <> -1
                If worker.CancellationPending Then Exit Do
    
                FileLines.Add(rdrfile.ReadLine)
            Loop
    
            rdrfile.Close()
    
            Dim writer As IO.StreamWriter = New IO.StreamWriter(sourcefile, False)
            Dim Columns As New List(Of String)
    
    
            For Each Str As String In FileLines
                If worker.CancellationPending Then Exit For
    
                strtemp = Str.Split(" "c)
                If Trim(strtemp(0)) = "FILENO" Then writer.Write(strtemp(11).Trim & vbCrLf)
            Next
    
            For Each filtereditem As String In Columns
                If worker.CancellationPending Then Exit For
                writer.Write(filtereditem & vbCrLf)
    
            Next
    
            writer.Close()
            FileLines.Clear()
    
            Do While intCount < 1
    
            Loop
    
            myProcess = New Process
            ' Start My process coding
            Dim smed As String
    
    
            Dim smedIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim smedOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim smedErr As System.IO.StreamReader = myProcess.StandardError
    
            smedIn.AutoFlush = True
            smedIn.Write("Run Second Command" & System.Environment.NewLine)
            smedIn.Write("exit" & System.Environment.NewLine)
    
            smed = smedOut.ReadToEnd()
    
            smedIn.Close()
            smedOut.Close()
            smedErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    
            Do While intCount < 1
    
            Loop
    
            Me.Label1.Text = "Run Third Command"
    
            myProcess = New Process
    
            Dim sfre As String
            ' Start My process coding
            Dim sfreIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sfreOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sfreErr As System.IO.StreamReader = myProcess.StandardError
    
            sfreIn.AutoFlush = True
            sfreIn.Write("Run Third Command" & System.Environment.NewLine)
            sfreIn.Write("exit" & System.Environment.NewLine)
    
            sfre = sfreOut.ReadToEnd()
    
            sfreIn.Close()
            sfreOut.Close()
            sfreErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    
            Do While intCount < 1
    
            Loop
    
            Me.Label1.Text = "Run Fourth Command"
    
            myProcess = New Process
    
            Dim scl As String
    
            Dim sclIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sclOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sclErr As System.IO.StreamReader = myProcess.StandardError
    
            sclIn.AutoFlush = True
            sclIn.Write("Run Fourth Command" & System.Environment.NewLine)
            sclIn.Write("exit" & System.Environment.NewLine)
    
            scl = sclOut.ReadToEnd()
    
            sclIn.Close()
            sclOut.Close()
            sclErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    
            Me.Label1.Text = "Edit the Data"
    
            Dim Open As String = IO.Path.Combine("Path")
            Dim Save As String = IO.Path.Combine("Path")
    
            Dim sb As New System.Text.StringBuilder
    
            Dim Lines =
                (From line In IO.File.ReadAllLines(Open)
                    Where line.Length > 0
            Select line).ToList
    
    
            For Each item In Lines
                If worker.CancellationPending Then Exit For
    
                Dim TempItem = item
                Dim Column1 = TempItem.Substring(0, TempItem.IndexOf(" "))
                TempItem = TempItem.Replace(Column1, "").Trim
                Dim Column2 = TempItem.Substring(0, 20)
    
                TempItem = TempItem.Replace(Column2, "").Trim
    
                Dim Parts = System.Text.RegularExpressions.Regex.Replace(TempItem.TrimStart, " {2,}", ",").Replace(" ", ",").Split(","c)
    
                sb.AppendLine(
                    String.Format("{0}{1}",
                                  Column1.PadRight(100, " "c),
                                  Column2.PadRight(100, " "c), ))
    
    
            Next
    
            IO.File.WriteAllText(Save, sb.ToString)
    
            Dim inputFile = Regex.Replace(IO.File.ReadAllText(Save), "[ ]{2,}", " ")
            IO.File.WriteAllText(Save, inputFile)
    
    
            If worker.CancellationPending Then e.Cancel = True
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  28. #28

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    Oh ok sorry Pradeep,

    I have removed the extra coding.

    I was under the impression that each section of coding had to be looped and if cancel was appending from any loop then it would all cancel? I'm sorry but its just I can see some sections that have no loops/do while like section 1, 2, 3 4 and 5?

    The bg worker has 6 sections:-

    Section 1

    Code:
     Dim intCount As Integer = 0
            Me.Label1.Text = "Run first command"
            myProcess = New Process
    
            Dim sid As String
            Dim sidIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sidOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sidErr As System.IO.StreamReader = myProcess.StandardError
            sidIn.AutoFlush = True
            sidIn.Write("Run First Command" & System.Environment.NewLine)
            sidIn.Write("exit" & System.Environment.NewLine)
            sid = sidOut.ReadToEnd()
            sidIn.Close()
            sidOut.Close()
            sidErr.Close()
            myProcess.Close()
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    Section 2

    Code:
    Me.Label1.Text = "Edit the data"
            Dim sourcefile As String = IO.Path.Combine("Path")
            Dim rdrfile As IO.StreamReader = IO.File.OpenText(sourcefile)
            Dim strtemp() As String
            Dim FileLines As New List(Of String)
            Do While rdrfile.Peek <> -1
                If worker.CancellationPending Then Exit Do
                FileLines.Add(rdrfile.ReadLine)
            Loop
            rdrfile.Close()
            Dim writer As IO.StreamWriter = New IO.StreamWriter(sourcefile, False)
            Dim Columns As New List(Of String)
            For Each Str As String In FileLines
                If worker.CancellationPending Then Exit For
                strtemp = Str.Split(" "c)
                If Trim(strtemp(0)) = "FILENO" Then writer.Write(strtemp(11).Trim & vbCrLf)
            Next
            For Each filtereditem As String In Columns
                If worker.CancellationPending Then Exit For
                writer.Write(filtereditem & vbCrLf)
            Next
            writer.Close()
            FileLines.Clear()
    Section 3

    Code:
    Me.Label1.Text = "Run Second Command"
    
            myProcess = New Process
            Dim smed As String
            Dim smedIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim smedOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim smedErr As System.IO.StreamReader = myProcess.StandardError
            smedIn.AutoFlush = True
            smedIn.Write("Run Second Command" & System.Environment.NewLine)
            smedIn.Write("exit" & System.Environment.NewLine)
            smed = smedOut.ReadToEnd()
            smedIn.Close()
            smedOut.Close()
            smedErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    Section 4

    Code:
     Me.Label1.Text = "Run Third Command"
    
            myProcess = New Process
    
            Dim sfre As String
            ' Start My process coding
            Dim sfreIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sfreOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sfreErr As System.IO.StreamReader = myProcess.StandardError
    
            sfreIn.AutoFlush = True
            sfreIn.Write("Run Third Command" & System.Environment.NewLine)
            sfreIn.Write("exit" & System.Environment.NewLine)
    
            sfre = sfreOut.ReadToEnd()
    
            sfreIn.Close()
            sfreOut.Close()
            sfreErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    Section 5

    Code:
     Me.Label1.Text = "Run Fourth Command"
    
            myProcess = New Process
    
            Dim scl As String
    
            Dim sclIn As System.IO.StreamWriter = myProcess.StandardInput
            Dim sclOut As System.IO.StreamReader = myProcess.StandardOutput
            Dim sclErr As System.IO.StreamReader = myProcess.StandardError
    
            sclIn.AutoFlush = True
            sclIn.Write("Run Fourth Command" & System.Environment.NewLine)
            sclIn.Write("exit" & System.Environment.NewLine)
    
            scl = sclOut.ReadToEnd()
    
            sclIn.Close()
            sclOut.Close()
            sclErr.Close()
            myProcess.Close()
    
            'Increment intCount by 1
            intCount += 1
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            End If
    Section 6

    Code:
    Me.Label1.Text = "Edit the Data"
    
            Dim Open As String = IO.Path.Combine("Path")
            Dim Save As String = IO.Path.Combine("Path")
    
            Dim sb As New System.Text.StringBuilder
    
            Dim Lines =
                (From line In IO.File.ReadAllLines(Open)
                    Where line.Length > 0
            Select line).ToList
    
    
            For Each item In Lines
                If worker.CancellationPending Then Exit For
    
                Dim TempItem = item
                Dim Column1 = TempItem.Substring(0, TempItem.IndexOf(" "))
                TempItem = TempItem.Replace(Column1, "").Trim
                Dim Column2 = TempItem.Substring(0, 20)
    
                TempItem = TempItem.Replace(Column2, "").Trim
    
                Dim Parts = System.Text.RegularExpressions.Regex.Replace(TempItem.TrimStart, " {2,}", ",").Replace(" ", ",").Split(","c)
    
                sb.AppendLine(
                    String.Format("{0}{1}",
                                  Column1.PadRight(100, " "c),
                                  Column2.PadRight(100, " "c), ))
    
    
            Next
    
            IO.File.WriteAllText(Save, sb.ToString)
    
            Dim inputFile = Regex.Replace(IO.File.ReadAllText(Save), "[ ]{2,}", " ")
            IO.File.WriteAllText(Save, inputFile)
    
    
            If worker.CancellationPending Then e.Cancel = True
    Also one more thing I use Exit Sub rather than Exit Do as that was showing an error, is that ok?
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  29. #29
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    ok. That's great.

    Now put each section code inside the If NOT worker.CancellationPending Then ... End If block.

    e.g.

    Code:
    If Not worker.CancellationPending Then
    
        '' section 1 code goes here...
    
    End If
    If Not worker.CancellationPending Then
    
        '' section 2 code goes here...
    
    End If
    
    .... repeat for all sections....
    
    
    '' Finally after your last section (i.e. just before End Sub)
    If worker.CancellationPending Then e.Cancel = True
    Ensure that each section is complete in itself. It should not have any dependency on any other section. So for example any file opened in one section should be closed in the same section itself etc.

    Put this code and you should be all set to go.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  30. #30

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    Many thanks Pradeep.

    Just one more thing I forgot to mention that I had a section 7, it is very small. I have included it below, is it ok?

    Section 7

    Code:
    If Not worker.CancellationPending Then
    dim contents as string = IO.File.ReadAllText("Path 1")
    IO.File.AppendAllText("Path 2", vbCrLf & contents) 
    End If
    
    If worker.CancellationPending Then e.Cancel = True
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  31. #31
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Help with cancelling background worker?

    So everything is working alright now?
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  32. #32

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: Help with cancelling background worker?

    Thank you a million Pradeep & JM.
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  33. #33

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: [RESOLVED] Help with cancelling background worker?

    Pradeep,

    Sorry one final question.

    One of my commands works like this, IF its cancelled then I have to run another command to undo what I have just done - this will only need to run if a text file has been created. Do you think the following coding looks ok? I have tested it and it does seem ok.

    Code:
       If Not worker.CancellationPending Then
    
                Me.lbl1.Text = "Run third command"
    
                'Create a new process  
                myProcess = New Process
    
                Dim sfre As String
                myProcess.StartInfo.FileName = "c:\windows\system32\cmd.exe"
                myProcess.StartInfo.UseShellExecute = False
                myProcess.StartInfo.CreateNoWindow = True
                myProcess.StartInfo.RedirectStandardInput = True
                myProcess.StartInfo.RedirectStandardOutput = True
                myProcess.StartInfo.RedirectStandardError = True
                myProcess.Start()
    
                Dim sfreIn As System.IO.StreamWriter = myProcess.StandardInput
                Dim sfreOut As System.IO.StreamReader = myProcess.StandardOutput
                Dim sfreErr As System.IO.StreamReader = myProcess.StandardError
    
                sfreIn.AutoFlush = True
                sfreIn.Write("command1" & System.Environment.NewLine)
                sfreIn.Write("exit" & System.Environment.NewLine)
    
                sfre = sfreOut.ReadToEnd()
    
                sfreIn.Close()
                sfreOut.Close()
                sfreErr.Close()
                myProcess.Close()
    
                'Increment intCount by 1
                intCount += 1
    
    
                If worker.CancellationPending Then
                    e.Cancel = True
               
        
                    If System.IO.File.Exists("Path") = True Then
                    Me.lbl1.Text = "Run other command"
                        myProcess = New Process
    
                        Dim sfree As String
                        myProcess.StartInfo.FileName = "c:\windows\system32\cmd.exe"
                        myProcess.StartInfo.UseShellExecute = False
                        myProcess.StartInfo.CreateNoWindow = True
                        myProcess.StartInfo.RedirectStandardInput = True
                        myProcess.StartInfo.RedirectStandardOutput = True
                        myProcess.StartInfo.RedirectStandardError = True
                        myProcess.Start()
    
                        Dim sfreeIn As System.IO.StreamWriter = myProcess.StandardInput
                        Dim sfreeOut As System.IO.StreamReader = myProcess.StandardOutput
                        Dim sfreeErr As System.IO.StreamReader = myProcess.StandardError
    
                        sfreeIn.AutoFlush = True
                        sfreeIn.Write("Command2" & System.Environment.NewLine)
                        sfreeIn.Write("exit" & System.Environment.NewLine)
    
                        sfree = sfreeOut.ReadToEnd()
    
                        sfreeIn.Close()
                        sfreeOut.Close()
                        sfreeErr.Close()
                        myProcess.Close()
    
                        'Increment intCount by 1
                        intCount += 1
                    End If
    
                    Exit Sub
                End If
    
            End If
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

  34. #34
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: [RESOLVED] Help with cancelling background worker?

    That would work. But I think making it as a separate section would be better.
    You have already divided your code into 7 sections. So you can add this as 8th one which does the rollback operation.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  35. #35

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2004
    Location
    U.K
    Posts
    771

    Re: [RESOLVED] Help with cancelling background worker?

    thanks mate.
    Please mark threads as resolved once the problem has been solved.
    I apprecaite all your help/advice given

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