2

I have some long running code:

Action GetSomeAction()=> () => {
//some code that takes a long time...
};

I run it like this:

_currentTask = Task.Run(GetSomeAction());

I need to ensure it restarts if it throws an exception. At first, I wrote this:

async Task EnsureTaskExecution()
{
    try
    {
        await _currentTask;
    }
    catch (Exception x)
    {
        Log.Error($"task exception: {x.GetType()} : {x.Message} {x.StackTrace} {x.InnerException?.GetType()} {x.InnerException?.Message}.");
        //...?
    }
}

How do I properly restart it though? Inserting this into catch block seems like bad idea, since it introduces recursion:

_currentTask = Task.Run(GetSomeAction());
await EnsureTaskExecution();

Are there any better options? Is there recommended pattern for this? This seems like an almost trivial task, yet I can't find anything.

user2363676
  • 331
  • 2
  • 10
  • IIRC C# tasks are not restartable, so what you'd do instead is basically make it recursive if it fails for a recoverable reason – Mgetz Jun 07 '18 at 14:57
  • A Task is not a thread to be restarted. It's a promise that something will run and produce something in the future. There's no "restarting" just like there's no "re-calling" a method. If you want to call something again, call it again. – Panagiotis Kanavos Jun 07 '18 at 14:57
  • @servy I don't think this is a dupe of that as this is specific to async/await which has very different semantics – Mgetz Jun 07 '18 at 14:59
  • BTW `GetSomeAction` can be any method that returns `void`. It doesn't have to be a lambda. If you had a `void GetSomeAction(){}` that you wanted to run in the background you coudl write `Task.Run(()=>GetSomeAction());` or even `Task.Run(GetSomeAction);` – Panagiotis Kanavos Jun 07 '18 at 14:59
  • @Mgetz There are async solutions there, although you can use any of the synchronous solutions and just add in the one `await` of the asynchronous operation you have. I have full confidence in their ability to add an `await` before the asynchronous method they're calling while everything else stays the same. The fundamental approach to structuring retry logic isn't actually any different, and that's what's being asked about. – Servy Jun 07 '18 at 15:00
  • 3
    Have a look at a the [Polly reliability framework](https://github.com/App-vNext/Polly) - this way you can specify a retry policy when you invoke asynchronous methods. – StuartLC Jun 07 '18 at 15:01

0 Answers0