0

Why does Task<T> not have a OnExit event that is invoked upon exiting through Exception or finishing regularly.
If I have an operation, for which I dont know when it will finish and whose result my continuing code does not depend on, I wont want to await it.
If im interested in the result however, whenever it may occur, I would have to await Task<T>.

Am I missing something here and such behaviour is already natively possible?

Naive delegate type of OnExit in my head would be something like this delegate void TaskExitHandler<T>(T result, Exception exception).

mfroeh
  • 293
  • 3
  • 9
  • 5
    You can just use [`.ContinueWith()`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.continuewith?view=net-5.0) for these purposes. By the way, if you don't await a task somewhere (or use a ContinueWith to check it) you will not see exceptions in the thread, so errors could go unnoticed. – Matthew Watson Jul 12 '21 at 10:23
  • @MatthewWatson Awesome, I didnt know about that. I'll look into it, thank you! – mfroeh Jul 12 '21 at 10:25
  • 1
    [Related](https://stackoverflow.com/a/12981091/1997232). – Sinatr Jul 12 '21 at 10:28
  • 2
    Please note _[Difference between await and ContinueWith](https://stackoverflow.com/questions/18965200/difference-between-await-and-continuewith)_ particularly [this](https://stackoverflow.com/a/18982576/585968) answer –  Jul 12 '21 at 10:36
  • As a side note, the name `OnExit` does not communicate failure. A better name would probably be `OnError`: `public static void OnError(this Task task, Action handler) { _ = task.ContinueWith(t => handler(t.Exception), default, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); }` – Theodor Zoulias Jul 12 '21 at 12:03
  • 1
    Or... you can just use `await` to do *the same exact thing*. – Stephen Cleary Jul 12 '21 at 13:29

0 Answers0