-
Dec 17th, 2021, 05:42 PM
#1
Thread Starter
Frenzied Member
[RESOLVED] Cancellation of task
I am trying to setup a task and when I click the stop button it should cancel. Everything I have read states I could use
Code:
cts.Token.ThrowIfCancellationRequested()
But when I do I get an error stating: System.OperationCanceledException: 'The operation was canceled.' and sends me into a break screen. I do have it in a try catch scenario. I am not sure why it is not being caught in my try and catch. Any idea? Did I miss somethign really stupid? I'm trying to grasp this task scheduling so I might no have done it correctly.
Code:
Try
' Is the Background Worker do some work?
If CmboDir.SelectedItem = "" Then
CmboDir.SelectedItem = "Common"
End If
If CmboDept.SelectedItem = "County_Shares" Then
' dPath = SharedDirPath
ElseIf CmboDept.SelectedItem = "All Depts." And CmboDir.SelectedItem = "H Drive" Then
AlldeptU = True
' dPath = DeptDirPath
ElseIf CmboDept.SelectedItem = "All Depts." And CmboDir.SelectedItem = "Common" Then
AlldeptC = True
dPath = DeptDirPath
Else
If CmboDir.SelectedItem = "H Drive" Then
dPath = UserDirPath & "\" & CmboDept.SelectedItem & "\Users\"
Else
dPath = DeptDirPath & "\" & CmboDept.SelectedItem & "\Common\"
End If
End If
'End If
cts = New CancellationTokenSource
SelectedDept = CmboDept.SelectedItem.ToString
If BtnSearch.Text = "Stop!!" Then
BtnSearch.Text = "Search"
dCancel = True
cts.Cancel()
Exit Sub
End If
If tab1 = True Then
Label4.Text = "Finding directories that '" & TxtBxGroupName.Text & "' is associated with under the '" & SelectedDept & "' " & CmboDir.SelectedItem & " Dir"
ElseIf tab2 = True And ChBxBrokenGUID.Checked = True Then
Label4.Text = "Finding broken GUIDs " & intDepthLimit & " levels deep under the '" & SelectedDept & "' " & CmboDir.SelectedItem & " Dir"
Else
Label4.Text = "Finding folders with broken Inheritance " & intDepthLimit & " levels under the '" & SelectedDept & "' " & CmboDir.SelectedItem & " Dir"
End If
searchLabel.Text = "Searching..."
Dim t As New Task(Sub()
For i = 0 To UBound(DeptNames)
If CBool(dCancel) Or cts.Token.IsCancellationRequested = True Then
' Clean up here, then...
Console.WriteLine("Cancelling per user request.")
cts.Token.ThrowIfCancellationRequested()
' Throw New OperationCanceledException()
Exit For
End If
dPath = DeptDirPath & "\" & DeptNames(i).ToString & "\Common\"
RecurseDirectory(dPath, intDepthLimit, intCurrentDepth, cts.Token)
Next
End Sub)
tasks.Add(t)
t.Start()
If cts.Token.IsCancellationRequested Then
' Clean up here, then...
cts.Token.ThrowIfCancellationRequested()
End If
BtnSave2Text.Enabled = False
BtnSearch.Text = "Stop!!"
start_time = Now
Catch ex As OperationCanceledException
BtnSearch.Text = "Search"
MessageBox.Show("Search has been cancelled.")
cancelNotification()
Catch ex As Exception
MessageBox.Show("We Have An Error:" + vbCrLf + vbCrLf + ex.Message)
'Debug.WriteLine(ex.Message)
End Try
-
Dec 17th, 2021, 11:57 PM
#2
Re: Cancellation of task
Make sure you don't have a check on Common Language runtime exceptions under Exception settings in Visual Studio.
See the following example for a basic example that will not break on a cancellation unless Common Language runtime exceptions is checked.
-
Dec 18th, 2021, 07:24 AM
#3
Thread Starter
Frenzied Member
Re: Cancellation of task
Thanks Karen, I will check that out on Monday when I'm back at work.
-
Dec 20th, 2021, 09:57 AM
#4
Re: Cancellation of task
A short example,
Code:
Private CTSource As New Threading.CancellationTokenSource()
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
Button2.Enabled = True
'setup the task
Dim someTask As Task
Dim CT As Threading.CancellationToken = CTSource.Token
someTask = New Task(Sub()
While True
If CT.IsCancellationRequested Then
' Clean up here, then...
' this causes an exception that says it is unhandled
' but it IS handled on the thread that started this task, just continue
CT.ThrowIfCancellationRequested()
End If
Threading.Thread.Sleep(100)
End While
End Sub, CTSource.Token)
Try
someTask.Start() 'start the task
Await someTask 'wait for it
Catch ex As Exception
If someTask.Status = TaskStatus.Canceled Then
Stop
'blah, blah
End If
Finally
Stop
CTSource.Dispose()
someTask.Dispose()
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
CTSource.Cancel() 'cancel
End Sub
-
Dec 20th, 2021, 11:43 AM
#5
Re: Cancellation of task
Originally Posted by phpman
Thanks Karen, I will check that out on Monday when I'm back at work.
See my GitHub repository for various code samples.
-
Dec 20th, 2021, 12:54 PM
#6
Thread Starter
Frenzied Member
Re: Cancellation of task
Ok, so I unchecked the System.OperationCanceledException under Exceptions settings. That fixed the breaking, still throws the error in the console, but it also does not go to the " Catch ex As OperationCanceledException" line. It just stops. When I put a break on that line so I can step into it, its brings up a file location box and looking for file "CancellationToken.cs". I think my code is correct, I think my .NET is messed up? I am running it on 4.7.2.
Thanks debasnett, I have looked a few examples, including Karen's, thank you, and I believe I am doing it correctly. I just can't figure out why my catches aren't working for this exception.
-
Dec 20th, 2021, 01:11 PM
#7
Re: Cancellation of task
Originally Posted by phpman
... Thanks debasnett, I have looked a few examples, including Karen's, thank you, and I believe I am doing it correctly. I just can't figure out why my catches aren't working for this exception.
Looking at yours and mine I can see structurally they are not the same.
-
Dec 20th, 2021, 02:42 PM
#8
Thread Starter
Frenzied Member
Re: Cancellation of task
If I make my code like yours, well as close as I can as I have a for next loop in mine, and I can't use the "Await" line as it tells me that "Await operator can only be used within an Async method" which it wants to change my button.click code to a Async function or sub. How does yours work but not mine? Is it the way I'm doing the for next loop and a recursive sub?
-
Dec 20th, 2021, 04:23 PM
#9
Thread Starter
Frenzied Member
Re: Cancellation of task
Ok so I made some changes and I have it working now. I was missing the cts.token in the task sub. And after I changed it around to be more like yours, dbasnet, thinks started to align and I could tell where my issues were. I think the biggest one was I was not using a cancel button, just renaming the search button and checking for name. Using a cancel button seemed to improve on the process.
Thank you both for pointing me in the right direction
Tags for this Thread
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
|