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.

6
  • IIRC C# tasks are not restartable, so what you'd do instead is basically make it recursive if it fails for a recoverable reason Commented Jun 7, 2018 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. Commented Jun 7, 2018 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 Commented Jun 7, 2018 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); Commented Jun 7, 2018 at 14:59
  • 3
    Have a look at a the Polly reliability framework - this way you can specify a retry policy when you invoke asynchronous methods. Commented Jun 7, 2018 at 15:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.