GeniuS BraiN GeniuS BraiN - 1 month ago 9
Vb.net Question

Exit method using Action that uses lambda expression

Let's say I have this method:

Sub Foo()
Dim ac As Action = Sub()
Console.WriteLine("Aborting")
Exit Sub ' This will exit the Action not the caller method.
End Sub
Console.WriteLine("1")
ac()
Console.WriteLine("2")
Console.WriteLine("3")
Console.WriteLine("4")
End Sub


I'm trying to use the
Action
to exit the method that calls it (
Foo
). Obviously, calling
Exit Sub
from inside the lambda expression will exit the action itself not the caller method.

So, is there a way to trigger
Exit Sub
of
Foo
from inside the Action's lambda expression?




Why am I trying to do this?

Well, I have a
BackgroundWorker.DoWork
event where I need to trigger the same action multiple times and I don't want to repeat myself. The normal approach is to create a separate method with all the repeated code and call the method when/where needed. Well, I can't do that because some of the "repeated code" can't be called from a separate method (e.g.
e.Result = False
&
Exit Sub
). That's why I thought of using an
Action
which might not be the right approach.

So is there any other way to handle this?




Edit (2)

Basically, I'm trying to do the following:

If condition1 Then Abort()
If condition2 Then Abort()
If condition3 Then Abort()


Instead of:

If condition1 Then
Abort()
Exit Sub
End If

If condition2 Then
Abort()
Exit Sub
End If

If condition3 Then
Abort()
Exit Sub
End If


Note: I can't combine
condition1
,
condition2
, and
condition3
together.

Answer

What you are trying to do with If condition1 Then Abort() is not the correct approach. Still you want to do the same here is a work around. You can even use try-catch block one level up i.e. outside Foo(). If you want to completely exit the Foo() but it depends on your logic.

Sub Foo()
    Const EXCP_MSSG_ABORT As String = "Aborting-101"
    Try
        Dim ac As Action = Sub()
                               Console.WriteLine("Aborting")
                               Throw New Exception(EXCP_MSSG_ABORT)
                           End Sub
        Console.WriteLine("1")
        ac()
        Console.WriteLine("2")
        Console.WriteLine("3")
        Console.WriteLine("4")
    Catch ex As Exception
        'Just ignore the exception and exit OR you want to be specific then check the message and exit
        'If ex.Message = EXCP_MSSG_ABORT Then
        '    Console.WriteLine("Exited from Action")
        'End If
    End Try
End Sub