When I lived in the C++ world, I found the subject of threading intuitive. Here in C#, I find I get completely lost, because there seems to be so many ways to do things.
Task
is probably the best choice most of the time but these are now so flexible that it is hard to know the best way.
I have what seems like a simple use case. I have an audio player that contains a function to fade the volume over a period of time. Because I don't want to block the calling code, I need the call to be fire-and-forget, so it seems like a case where it needs to do its thing on a separate thread. The problem is that the parent audio player can be disposed of while a volume fade is in progress.
I would be extremely grateful for any tips about how to best handle this.
The outline of the code could not be simpler:
public class AudioPlayer
{
public void FadeVolume( double targetVolume, double fadeTimeSeconds )
{
}
}
What I have tried:
I've tried a menagerie of
Task
,
await
,
Wait()
,
Task.Run()
, and probably most of the rest of the available
Task
function calls, but I still don't seem to be able to find a way to handle this without some nasty exception or other.
Note that I do realise I may have to accept some kinds of exception (e.g.
TaskCanceledException
), which I aim to simply catch, maybe log, and then forget.
Mostly what I am concerned about is simply that I am handling things safely.