如何获取长 运行 任务的状态

How to get status of long running task

为什么我的 Task return 的 Status 是“WaitingForActivasion”而不是“运行”?
如果我删除 Task.Run 我会陷入 while 循环,所以我假设它不是 运行 异步的。

public class StateManagerTest
{
    [Fact]
    public void Start_TaskStatus()
    {
        StateManager manager = new StateManager();
        manager.Start();

        Assert.True(manager.Status == System.Threading.Tasks.TaskStatus.Running.ToString());
    }
}

public class StateManager
{
    private CancellationTokenSource cts = new();
    private Task updateTask;
    public HashSet<StateItem> StateItems { get; private set; }
    public Provider Provider { get; private set; }
    public List<OutputService> OutputServices { get; private set; }

    public string Status
    {
        get => updateTask.Status.ToString();
    }

    public StateManager()
    {
        StateItems = new();
        OutputServices = new();
        Provider = new();
    }

    public void Stop()
    {
        cts.Cancel();
    }

    public void Start()
    {
        updateTask = Task.Run(() => Update(cts.Token))
            .ContinueWith(t => Debug.WriteLine(t.Exception.Message), TaskContinuationOptions.OnlyOnFaulted);
    }

    private async Task Update(CancellationToken token)
    {
        while (true)
        {
            // get changes from outputs
            Dictionary<StateItem, object> changes = new Dictionary<StateItem, object>();
            foreach (var service in OutputServices)
            {
                var outputChanges = await service.GetChanges();
                foreach (var change in outputChanges)
                    changes.TryAdd(change.Key, change.Value);
            }

            // write changes to provider source
            await Provider.PushChanges(changes);

            // update state
            await Provider.UpdateStateItems();

            // update all services
            foreach (var service in OutputServices)
                await service.UpdateSource();

            if (token.IsCancellationRequested)
                return;
        }
    }
}

正如其他人所指出的,WaitingForActivation is the correct state for a Promise Task that is not yet completed。一般来说,我建议不要使用 Task.StatusContinueWith;它们是 async/await 存在之前的遗迹。

How to get status of long running task

我相信你会想要progress reporting,这是你自己完成的。如果您想要简单的文本更新,IProgress<T> 中的 T 可以是 string,如果您想要百分比更新,则可以是 double,或者自定义 struct如果你想要更复杂的更新。