I have actions that return void. but I need the call to keep the current scope open while it runs.
public class CancellationHelper
{
CancellationTokenSource _cts;
public void Run(Action<CancellationToken> action)
{
if (_cts != null)
{
return;
}
using (_cts = new CancellationTokenSource())
{
action(_cts.Token);
}
}
}
if the action is async, the _cts will be disposed before the method completes. the return type is void, so I can’t just await it… I’ve read you are supposed to avoid Task.Run and favor async/await, but I don’t see how to do this for using clauses.
Is await Task.Run(action); dirty? is this spinning up another ‘task’ or thread to wait for something that spins up a task or thread?
It sounds like
actionis anasync voidmethod.Don’t do that.
It is impossible to find out when an
async voidmethod finishes.Instead, you need to make your method accept a
Func<Task>.You can then write
await action();.