首页 > 解决方案 > 如何使用扩展方法跟踪任务的状态?

问题描述

我是异步编程的新手。尝试创建正确的扩展方法,如果它已经改变可以打印任务的状态。但我不知道该怎么做。这就是我现在所拥有的:

static class MyAsync
{
    static void Main()
    {
        Task t = MyAsync.PrintCountPrimesAsync(35);
        t.Tracking();
        Thread.Sleep(1000);
    }

    public static async Task PrintCountPrimesAsync(int n) =>
        Console.WriteLine($"CountOfPrimes = { await CustomMath.GetPrimesCountAsync(100000, 100000)}");


    public static async Task Tracking(this Task task)
    {
        await Task.Run(() =>
        {
            TaskStatus current = task.Status;
            while (!task.IsCompleted)
            {
                if (current != task.Status)
                {
                    Console.WriteLine(task.Status);
                    current = task.Status;
                }
            }
        });
    }
}

class CustomMath
{
    public static Task<int> GetPrimesCountAsync(int start, int count)
    {
        return Task.Run(() =>
            ParallelEnumerable.Range(start, count).Count(n =>
                Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i => n % i > 0)));
    }
}

标签: c#

解决方案


对此的理想答案是“不要”,但如果您绝对必须,则ContinueWith充当可能适合此处的回调:

public static void Tracking(this Task task)
    => _ = task.ContinueWith(static x => Console.WriteLine(x.Status));

这仅跟踪完成(无论有无故障),但是:无论如何,这几乎是唯一有趣且可靠的状态转换。


推荐阅读