-
May 21st, 2012, 05:04 AM
#1
Thread Starter
Fanatic Member
[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
-
May 21st, 2012, 05:36 AM
#2
Hyperactive Member
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
-
May 21st, 2012, 05:39 AM
#3
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?
-
May 21st, 2012, 05:47 AM
#4
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:
'' Declare an array of BackgroundWorkers Dim MyBackgroundWorkers() As BackgroundWorker Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load '' add all your BackgroundWorkers to the array MyBackgroundWorkers = New BackgroundWorker() {BackgroundWorker1, BackgroundWorker2, BackgroundWorker3, BackgroundWorker4, BackgroundWorker5} End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click '' now you can Cancel all of them in a loop For Each bgw In MyBackgroundWorkers If bgw.IsBusy Then bgw.CancelAsync() End If Next 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.
-
May 21st, 2012, 05:50 AM
#5
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.
-
May 21st, 2012, 10:52 AM
#6
Thread Starter
Fanatic Member
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
-
May 21st, 2012, 12:15 PM
#7
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.
-
May 21st, 2012, 06:47 PM
#8
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.
-
May 22nd, 2012, 02:37 AM
#9
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
-
May 22nd, 2012, 02:49 AM
#10
Re: Help with cancelling background worker?
You didn't like my CodeBank examples Pradeep?
-
May 22nd, 2012, 04:00 AM
#11
Thread Starter
Fanatic Member
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
-
May 22nd, 2012, 04:03 AM
#12
Thread Starter
Fanatic Member
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
-
May 22nd, 2012, 04:07 AM
#13
Re: Help with cancelling background worker?
-
May 22nd, 2012, 05:03 AM
#14
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.
-
May 22nd, 2012, 05:11 AM
#15
Thread Starter
Fanatic Member
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
-
May 22nd, 2012, 05:16 AM
#16
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.
-
May 22nd, 2012, 05:33 AM
#17
Re: Help with cancelling background worker?
Originally Posted by frankwhite
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.
-
May 22nd, 2012, 05:53 AM
#18
Thread Starter
Fanatic Member
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
-
May 22nd, 2012, 06:59 AM
#19
Re: Help with cancelling background worker?
Originally Posted by frankwhite
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.
-
May 22nd, 2012, 07:13 AM
#20
Re: Help with cancelling background worker?
Have a look at this:
vb.net 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 '' your other code If worker.CancellationPending Then Exit Do Loop '' your other code For Each Str As String In FileLines '' your other code If worker.CancellationPending Then Exit For Next For Each filtereditem As String In Columns '' your other code If worker.CancellationPending Then Exit For Next '' your other code For Each item In Lines '' your other code If worker.CancellationPending Then Exit For Next '' your other code '' just before End Sub If worker.CancellationPending Then e.Cancel = True End Sub
-
May 22nd, 2012, 07:21 AM
#21
Thread Starter
Fanatic Member
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
-
May 22nd, 2012, 08:07 AM
#22
Re: Help with cancelling background worker?
Originally Posted by Pradeep1210
Have a look at this:
vb.net 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
'' your other code
If worker.CancellationPending Then Exit Do
Loop
'' your other code
For Each Str As String In FileLines
'' your other code
If worker.CancellationPending Then Exit For
Next
For Each filtereditem As String In Columns
'' your other code
If worker.CancellationPending Then Exit For
Next
'' your other code
For Each item In Lines
'' your other code
If worker.CancellationPending Then Exit For
Next
'' your other code
'' just before End Sub
If worker.CancellationPending Then e.Cancel = True
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.
-
May 22nd, 2012, 08:28 AM
#23
Thread Starter
Fanatic Member
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
-
May 22nd, 2012, 08:50 AM
#24
Re: Help with cancelling background worker?
How about the obvious:
vb Code:
If Not e.CancellationPending Then 'Do the work here. End If
-
May 22nd, 2012, 10:29 AM
#25
Re: Help with cancelling background worker?
Originally Posted by jmcilhinney
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
-
May 22nd, 2012, 11:19 AM
#26
Thread Starter
Fanatic Member
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
-
May 22nd, 2012, 12:20 PM
#27
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
-
May 22nd, 2012, 03:05 PM
#28
Thread Starter
Fanatic Member
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
-
May 22nd, 2012, 04:34 PM
#29
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.
-
May 22nd, 2012, 05:25 PM
#30
Thread Starter
Fanatic Member
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
-
May 22nd, 2012, 10:35 PM
#31
Re: Help with cancelling background worker?
So everything is working alright now?
-
May 23rd, 2012, 04:03 AM
#32
Thread Starter
Fanatic Member
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
-
May 23rd, 2012, 12:01 PM
#33
Thread Starter
Fanatic Member
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
-
May 23rd, 2012, 01:53 PM
#34
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.
-
May 23rd, 2012, 02:56 PM
#35
Thread Starter
Fanatic Member
Re: [RESOLVED] Help with cancelling background worker?
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|