I'm not sure that your worry is justified, but I'm going to assume that it is.
The problem with your code that uses Task.Delay()
is that you're not actually canceling the operation. This might mean that you're wasting resources or misinforming your users (you tell them that the operation timed out, while the operation is still running and will most likely complete successfully).
Now, if you want to make sure that the cancellation token starts ticking only after the operation is started, then do that:
var source = new CancellationTokenSource();
var task = SomeOperationAsync(source.Token);
source.CancelAfter(TimeSpan.FromMilliseconds(n));
await task;
If you do this often, you might want to encapsulate this logic into a method (might need a better name):
public static async Task WithTimeoutAfterStart(
Func<CancellationToken, Task> operation, TimeSpan timeout)
{
var source = new CancellationTokenSource();
var task = operation(source.Token);
source.CancelAfter(timeout);
await task;
}
Usage:
await WithTimeoutAfterStart(
ct => SomeOperationAsync(ct), TimeSpan.FromMilliseconds(n));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…