none
Catch OperationCanceledException RRS feed

  • Question

  • Hi! 

    I need to Catch an OperationCancelledException from a Function

    I can´t  MsgBox("Cancelled.") when pressing the cancel button (Button2)

    (https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks)

    I suppose that the problem is that my Function is not an Async Function, but could you please help me to Catch this in the Button1_Click sub?

    Thank you very much!

    ' Form contains 2 Buttons and 1 Label
    
    Public Class Form1
    
        Dim cts As Threading.CancellationTokenSource
    
        Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Try
                cts = New Threading.CancellationTokenSource()
    
                Dim Task01 As New Task(Of String)(Function() Calcular("I like ", cts.Token)) : Task01.Start()
                Dim cadena As String = Await Task01
                MsgBox(cadena)
    
            Catch ex As OperationCanceledException
                MsgBox("Cancelled.")
            End Try
        End Sub
    
        Function Calcular(text As String, ct As Threading.CancellationToken) As String
            For i = 1 To 10
                Threading.Thread.Sleep(500)
                ct.ThrowIfCancellationRequested()
            Next i
    
            Return text & "bacon."
        End Function
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            If cts IsNot Nothing Then cts.Cancel()
        End Sub
    
    End Class



    • Edited by vanerio Saturday, September 8, 2018 12:11 AM
    Saturday, September 8, 2018 12:10 AM

Answers

  • Okay,

    Here is something that might work for you in regards to the "only works" when not in debug mode. Remove the Form Shown event. Let the exception be throw, press the red X as shown below followed by checking the check box below. Now run the project again and the exception should be trapped.

    Revised code

    Public Class Form1
        Dim _cts As Threading.CancellationTokenSource
        Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Try
                _cts = New Threading.CancellationTokenSource()
    
                Dim task01 As New Task(Of String)(
                    Function()
                        Return Calcular("I like ", _cts.Token)
                    End Function)
    
                task01.Start()
    
                Dim cadena As String = Await task01
                If Not String.IsNullOrWhiteSpace(cadena) Then
                    MessageBox.Show(cadena)
                End If
    
    
            Catch ex As OperationCanceledException
                MessageBox.Show($"Cancelled: {ex.Message}, have no idea what you like")
            End Try
        End Sub
        Function Calcular(pText As String, pToken As Threading.CancellationToken) As String
    
            For i = 1 To 5
                Threading.Thread.Sleep(500)
                If pToken.IsCancellationRequested Then
                    pToken.ThrowIfCancellationRequested()
                End If
            Next i
    
            Return $"{pText} bacon"
    
        End Function
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            If _cts IsNot Nothing Then
                _cts.Cancel()
            End If
        End Sub
    End Class
    
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by vanerio Monday, September 10, 2018 12:25 PM
    Monday, September 10, 2018 12:05 PM
    Moderator

All replies

  • See the following

    https://code.msdn.microsoft.com/Populate-DataGridView-via-a3ede35a/sourcecode?fileId=163017&pathId=1537415694


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, September 8, 2018 12:57 AM
    Moderator
  • Thank you Karen!

    I have been looking the project but unfortunately  I can´t find the solution there. 

    I can´t make the jump to the 'Catch ex As OperationCanceledException' section when 'ThrowIfCancellationRequested' is used (inside the Function).


    • Edited by vanerio Saturday, September 8, 2018 9:20 AM
    Saturday, September 8, 2018 9:15 AM
  • Sorry, most have been not thinking properly. In the following example you need to run from Windows Explorer.

    Public Class Form1
        Dim _cts As Threading.CancellationTokenSource
        Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Try
                _cts = New Threading.CancellationTokenSource()
    
                Dim task01 As New Task(Of String)(Function() Calcular("I like ", _cts.Token)) : task01.Start()
                Dim cadena As String = Await task01
                MessageBox.Show(cadena)
    
            Catch ex As OperationCanceledException
                MessageBox.Show($"Cancelled: {ex.Message}, have no idea what you like")
            End Try
        End Sub
        Function Calcular(pText As String, pToken As Threading.CancellationToken) As String
    
            For i = 1 To 5
                Threading.Thread.Sleep(500)
                If pToken.IsCancellationRequested Then
                    pToken.ThrowIfCancellationRequested()
                End If
            Next i
    
            Return $"{pText} bacon"
    
        End Function
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            If _cts IsNot Nothing Then
                _cts.Cancel()
            End If
        End Sub
    
        Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            If Debugger.IsAttached Then
                Button1.Enabled = False
                Button2.Enabled = False
                MessageBox.Show("You need to run from Windows Explorer")
            End If
        End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, September 8, 2018 11:24 AM
    Moderator
  • Hi Karen!

    You are completly correct! It works when running from Windows Explorer.

    Is there any way to make it work even when Debugger.IsAttached = True?

    Thank you very much!!!

    Saturday, September 8, 2018 11:39 AM
  • Hi Karen!

    You are completly correct! It works when running from Windows Explorer.

    Is there any way to make it work even when Debugger.IsAttached = True?

    Thank you very much!!!

    No, otherwise I would have given you a way.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, September 8, 2018 1:43 PM
    Moderator
  • Please, let me ask you something else:

    Could this be problematic in any case if I keep this code?

    Is there any other way that could be more 'healthy' for my program?

    Like returning a flag: 

    Public Class Form1 Dim _cts As Threading.CancellationTokenSource Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Try _cts = New Threading.CancellationTokenSource() Dim task01 As New Task(Of String)(Function() Calcular("I like ", _cts.Token)) : task01.Start() Dim cadena As String = Await task01

    If cadena = Nothing Then pToken.ThrowIfCancellationRequested() ' <--------

    MessageBox.Show(cadena) Catch ex As OperationCanceledException MessageBox.Show($"Cancelled: {ex.Message}, have no idea what you like") End Try End Sub Function Calcular(pText As String, pToken As Threading.CancellationToken) As String For i = 1 To 5 Threading.Thread.Sleep(500)

    If pToken.IsCancellationRequested Then Return Nothing ' <--------

    Next i Return $"{pText} bacon" End Function Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click If _cts IsNot Nothing Then _cts.Cancel() End If End Sub Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown If Debugger.IsAttached Then Button1.Enabled = False Button2.Enabled = False MessageBox.Show("You need to run from Windows Explorer") End If End Sub End Class

    Or do you recommend another way to handle it?

    Thank you very much Karen!!!



    • Edited by vanerio Saturday, September 8, 2018 1:56 PM
    Saturday, September 8, 2018 1:55 PM
  • Hi,

    Do you resolve the issue?

    I think you can write try..catch.. in Function Calcular,Is this okay?

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, September 10, 2018 6:33 AM
  • One thing I would change is instead of returning Nothing, return an empty string and check for an empty string on returning from the caller.

    If pToken.IsCancellationRequested Then Return ""


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, September 10, 2018 10:19 AM
    Moderator
  • A Try.Catch in the Function would work prefectly, but I wanted to Run more tasks (Task01, Task02, Task03, etc) and a common Try.Catch for all of them is just perfect.

    But thank you!!

    Monday, September 10, 2018 11:10 AM
  • Ok! Thanks!

    But let me ask it again, because, for me, it doesn´t really matter if the previous option (the one that only works when Debugger.IsAttached = False) is not a problem, I would keep it, so I would prefer this option in case it is not unhealthy and it won´t cause any problems

    What do you think?

    Thank you!!!!

    Monday, September 10, 2018 11:15 AM
  • Okay,

    Here is something that might work for you in regards to the "only works" when not in debug mode. Remove the Form Shown event. Let the exception be throw, press the red X as shown below followed by checking the check box below. Now run the project again and the exception should be trapped.

    Revised code

    Public Class Form1
        Dim _cts As Threading.CancellationTokenSource
        Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Try
                _cts = New Threading.CancellationTokenSource()
    
                Dim task01 As New Task(Of String)(
                    Function()
                        Return Calcular("I like ", _cts.Token)
                    End Function)
    
                task01.Start()
    
                Dim cadena As String = Await task01
                If Not String.IsNullOrWhiteSpace(cadena) Then
                    MessageBox.Show(cadena)
                End If
    
    
            Catch ex As OperationCanceledException
                MessageBox.Show($"Cancelled: {ex.Message}, have no idea what you like")
            End Try
        End Sub
        Function Calcular(pText As String, pToken As Threading.CancellationToken) As String
    
            For i = 1 To 5
                Threading.Thread.Sleep(500)
                If pToken.IsCancellationRequested Then
                    pToken.ThrowIfCancellationRequested()
                End If
            Next i
    
            Return $"{pText} bacon"
    
        End Function
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            If _cts IsNot Nothing Then
                _cts.Cancel()
            End If
        End Sub
    End Class
    
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by vanerio Monday, September 10, 2018 12:25 PM
    Monday, September 10, 2018 12:05 PM
    Moderator
  • Ok! Thanks!

    But let me ask it again, because, for me, it doesn´t really matter if the previous option (the one that only works when Debugger.IsAttached = False) is not a problem, I would keep it, so I would prefer this option in case it is not unhealthy and it won´t cause any problems

    What do you think?

    Thank you!!!!

    Look at my last reply.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, September 10, 2018 12:06 PM
    Moderator
  • Thank you very much Karen!

    Unfortunately I don´t have "Except when thrown from" available as I am still using Visual Studio 2015 (I can´t install Visual Studio 2017 in my computer)

    But I will keep it in mind in case I could update!!

    So I mark your last reply as answer as this should be the solution to my problem!!

    Thank you very much again, great help!!!


    • Edited by vanerio Monday, September 10, 2018 12:26 PM
    Monday, September 10, 2018 12:25 PM