简体   繁体   中英

How to get status of long running task

Why does the Status of my Task return "WaitingForActivasion" instead of "Running" ?
If I remove Task.Run I get stuck in the while loop, so I assume its not running asynchronous.

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;
        }
    }
}

As others have noted, WaitingForActivation is the correct state for a Promise Task that is not yet completed . In general, I recommend not using Task.Status or ContinueWith ; they are relics from a time before async / await existed.

How to get status of long running task

I believe you would want progress reporting , which is done yourself. The T in IProgress<T> can be a string if you want a simple text update, or a double if you want a percentage update, or a custom struct if you want a more complex update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM