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
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:cts.Token.ThrowIfCancellationRequested()
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




Reply With Quote
