Sometimes you just need to kick off a process and not care about what happens to it. The old “fire-and-forget” scenario.
Sometimes you want an action to happen after a certain duration of time. I recently had an application where I would detect a lost connection, and then enter a reconnect loop. After a set amount of time (say, 30 seconds), I want to stop trying and proclaim the connection dead. It was a WPF application, so I didn’t want to lock up the UI.
But First
If you’re doing this, just be careful. There are a lot of reasons to hesitate do this inside of an ASP.NET application, for example, so use caution.
Unit Testing
Kicking off tasks is great and all, but how the heck do you test that? You want to make sure that the deferred action actually took place, but its pretty crazy to write a test to sleep the test execution until you’ve waited a sufficient amount of time. If you do that, your tests will take longer to run, other people won’t want to run them, when there’s a lot of test load it might take too long… you’re asking for trouble.
Defer
Here’s the basics of the code:
The tasks are stored in a concurrent dictionary so they can be awaited later, if you want. This is really useful for unit testing because you can await the completion of the deferred task, asserting that the correct code was executed.
This can (and I have) be extended to use Func<Task> as well as just fire-and-forget tasks without any delay. The full source is available on GitHub here. Eventually I will probably make a NuGet package with it, but, for now, there’s the code.