c# - 如何使用扩展方法跟踪任务的状态?
问题描述
我是异步编程的新手。尝试创建正确的扩展方法,如果它已经改变可以打印任务的状态。但我不知道该怎么做。这就是我现在所拥有的:
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)));
}
}
解决方案
对此的理想答案是“不要”,但如果您绝对必须,则ContinueWith
充当可能适合此处的回调:
public static void Tracking(this Task task)
=> _ = task.ContinueWith(static x => Console.WriteLine(x.Status));
这仅跟踪完成(无论有无故障),但是:无论如何,这几乎是唯一有趣且可靠的状态转换。
推荐阅读
- opencv - 在python空闲错误中导入openCV:共享对象文件
- amazon-web-services - 我应该如何测试我的“无服务器”(API Gateway/Lambda/ECS)应用程序?
- javascript - 如何在 24 小时后执行操作?(不使用 setTimeout)
- javascript - 盖茨比中的 Polyfilling 集
- windows - DCMTK movecu 错误:响应成功但未收到文件
- apache-spark-sql - 使用 sparkSQL 时,如何广播 tempTable 而不是“排序合并连接”?
- javascript - 使导航栏的背景在滚动时发生变化
- c++ - 运算符重载 [] 是否也会自动重载算术?
- performance - Android Studio 变得缓慢且无响应
- shopify - Shopify 产品系列页面上的产品图片尺寸不断变化