I have a general question on how to track an asynchronous task that starts when an object is placed in .Net. I have a class created around Stephen Cleary Dispose means the abolition of the paradigm . The problem is that Dispose is a void, so it is not possible to directly track this task.
I created another static class that has a list of tasks that allow me to do something similar at the end of my program to make sure that all uninstall tasks end before the program exits.
public async Task WaitForAllDanglingTasks(CancellationToken token)
{
while (_dangling.Count > 0)
{
token.ThrowIfCancellationRequested();
var t = await Task.WhenAny(_dangling.ToArray()).DetachContext();
await _lock.WaitAsync(token).DetachContext();
try
{
_dangling.Remove(t);
}
finally
{
_lock.Release();
}
}
}
Is this a good approach? Is there something better or is it even necessary?
EDIT: , , , , SerialPort. , , . , .
, , ( ). , - IP. , , RX, . .
async Task StartService(args, token)
{
ServiceTask = Task.Run(async () => await LongRunning(args, token))
.continuewith(t => cleanup(args));
ServiceTask.TrackDisposal();
await LongRunningReady(token);
}
async Task LongRunning(args, token)
{
using( var combined = CreateLinkedSource(_dispose.token, token))
{
DoWork(args);
}
}
void Dispose()
{
_dispose.Cancel();
}
, , ContinueWith. , , Continuewith, , , . , ServiceTask.
, . , - , , , .
, AsyncContext AsyncEx . , ManyConsole .