dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.44k stars 4.76k forks source link

[API Proposal]: Task manager #108372

Open Mr0N opened 1 month ago

Mr0N commented 1 month ago

Background and motivation

I suggest adding a task manager with a rating system."

API Proposal

class Manager
{
    record InfoOfTask(Task task, long rating);
    int _maxCountsTask;

    List<InfoOfTask> _lsTask = new List<InfoOfTask>();
    public Manager(int maxCountsTask)
    {
        _maxCountsTask = maxCountsTask;

    }

    public void Add(Action action, int rating)
    {
        var task = new Task(action);
        checked
        {
            long range = (long)rating + DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            _lsTask.Add(new InfoOfTask(task, range));
        }

    }
    public void Run()
    {
        var en = _lsTask.ToArray().OrderBy(a => a.rating);
        int count = 0;
        var ls = new List<Task>();
        foreach (var element in en)
        {
            count++;
            element.task.ContinueWith(a =>
            {
                throw new Exception("Exception", a.Exception);
            }, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
            if (count >= _maxCountsTask)
            {

                Task.WaitAny(ls.ToArray());
                int taskCounts = ls.RemoveAll(a => (int)a.Status > 4);
                count -= taskCounts;
            }
            element.task.Start();
            ls.Add(element.task);
        }
    }

API Usage

class Cat
{
    public void Go()
    {
        var manager = new Manager(10);
        var random =new Random();
        for (int i = 0; i < 100; i++)
        {
            object item = i;
            int rating = random.Next(1, 1000);
            manager.Add(() => Console.WriteLine($"item:{item} rating:{rating} thread:{Thread.CurrentThread.ManagedThreadId}"),rating);
        }

        manager.Run();
    }

}

Alternative Designs

No response

Risks

No response

dotnet-policy-service[bot] commented 1 month ago

Tagging subscribers to this area: @dotnet/area-system-threading-tasks See info in area-owners.md if you want to be subscribed.

huoyaoyuan commented 1 month ago

It's just a PriorityQueue<Action, int>.