如何在取消任务之前跟踪任务花费的时间

How to track time spent by a task before getting cancelled

我正在做一个

Task.Delay(durationInMilliseconds, cancellationToken).ContinueWith(taskResult =>{
    if (!taskResult.IsCanceled && taskResult.IsCompleted)
    {
        //Do something
    }
    else if (taskResult.IsCanceled)
    {
        //persist the time spent before task got cancelled
    }
});

如何跟踪任务 运行 在被取消之前的持续时间?

使用Stopwatch class。它包含一个高分辨率计时器。每当任务开始时启动计时器,当您想检查经过的时间时,如果它是属性,请调用一个。

使用方法:

Stopwatch stopwatch = Stopwatch.StartNew();

long elapsedMillis = stopwatch.ElapsedMilliseconds;