Search code examples
c#destructor

C#, is there 'Defer Call' like golang?


golang support 'Defer Call' and when c++, I use this trick(?).

struct DeferCall
{
   DeferCall() {}
   ~DeferCall() { doSomeThing(); }
}

void SomeMethod()
{
    DeferCall deferCall;
    ...
}

how can I do this in c# ?

I need like this golang defer tutorial


Solution

  • I picked up the following definition of the Defer Call in GoLang from here

    A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.

    C# version:

    Option 1:

    • Use a Task API
    • Wrap your DeferCall method in the Task
    • Execute at the right time either Manually using Start() method or for the function post which you want to continute, wrap that in another Task object and execute using ContinueWithAPI, which will chain tasks to execute one after another

    Option 2:

    • Can make whole call chain Async-Await, where everything post await keyword is executed the main call finish, this is standard Asynchronous implementation