动作中的 C# 异步
C# async within an action
我想编写一个接受多个参数的方法,包括一个动作和一个重试次数并调用它。
所以我有这个代码:
public static IEnumerable<Task> RunWithRetries<T>(List<T> source, int threads, Func<T, Task<bool>> action, int retries, string method)
{
object lockObj = new object();
int index = 0;
return new Action(async () =>
{
while (true)
{
T item;
lock (lockObj)
{
if (index < source.Count)
{
item = source[index];
index++;
}
else
break;
}
int retry = retries;
while (retry > 0)
{
try
{
bool res = await action(item);
if (res)
retry = -1;
else
//sleep if not success..
Thread.Sleep(200);
}
catch (Exception e)
{
LoggerAgent.LogException(e, method);
}
finally
{
retry--;
}
}
}
}).RunParallel(threads);
}
RunParallel 是 Action 的扩展方法,它看起来像这样:
public static IEnumerable<Task> RunParallel(this Action action, int amount)
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < amount; i++)
{
Task task = Task.Factory.StartNew(action);
tasks.Add(task);
}
return tasks;
}
现在,问题是:线程正在消失或崩溃,而没有等待操作完成。
我写了这个示例代码:
private static async Task ex()
{
List<int> ints = new List<int>();
for (int i = 0; i < 1000; i++)
{
ints.Add(i);
}
var tasks = RetryComponent.RunWithRetries(ints, 100, async (num) =>
{
try
{
List<string> test = await fetchSmthFromDb();
Console.WriteLine("#" + num + " " + test[0]);
return test[0] == "test";
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
return false;
}
}, 5, "test");
await Task.WhenAll(tasks);
}
fetchSmthFromDb
是一个简单的任务>,它从数据库中获取一些东西,并且在这个例子之外调用时工作得很好。
每当调用 List<string> test = await fetchSmthFromDb();
行时,线程似乎正在关闭并且 Console.WriteLine("#" + num + " " + test[0]);
甚至没有被触发,调试断点时也从未命中。
最终工作代码
private static async Task DoWithRetries(Func<Task> action, int retryCount, string method)
{
while (true)
{
try
{
await action();
break;
}
catch (Exception e)
{
LoggerAgent.LogException(e, method);
}
if (retryCount <= 0)
break;
retryCount--;
await Task.Delay(200);
};
}
public static async Task RunWithRetries<T>(List<T> source, int threads, Func<T, Task<bool>> action, int retries, string method)
{
Func<T, Task> newAction = async (item) =>
{
await DoWithRetries(async ()=>
{
await action(item);
}, retries, method);
};
await source.ParallelForEachAsync(newAction, threads);
}
问题出在这一行:
return new Action(async () => ...
您使用异步 lambda 启动异步操作,但没有 return 等待的任务。 IE。它 运行 在工作线程上运行,但您永远不会知道它何时完成。并且您的程序在异步操作完成之前终止 - 这就是您看不到任何输出的原因。
需要:
return new Func<Task>(async () => ...
更新
首先,您需要拆分方法的职责,因此不要将重试策略(不应硬编码为检查布尔结果)与 运行ning 任务并行。
然后,如前所述,您 运行 您的 while (true)
循环 100 次,而不是并行处理。
正如@MachineLearning 指出的那样,使用 Task.Delay
而不是 Thread.Sleep
。
总体而言,您的解决方案如下所示:
using System.Collections.Async;
static async Task DoWithRetries(Func<Task> action, int retryCount, string method)
{
while (true)
{
try
{
await action();
break;
}
catch (Exception e)
{
LoggerAgent.LogException(e, method);
}
if (retryCount <= 0)
break;
retryCount--;
await Task.Delay(millisecondsDelay: 200);
};
}
static async Task Example()
{
List<int> ints = new List<int>();
for (int i = 0; i < 1000; i++)
ints.Add(i);
Func<int, Task> actionOnItem =
async item =>
{
await DoWithRetries(async () =>
{
List<string> test = await fetchSmthFromDb();
Console.WriteLine("#" + item + " " + test[0]);
if (test[0] != "test")
throw new InvalidOperationException("unexpected result"); // will be re-tried
},
retryCount: 5,
method: "test");
};
await ints.ParallelForEachAsync(actionOnItem, maxDegreeOfParalellism: 100);
}
您需要使用 AsyncEnumerator NuGet Package 才能使用 System.Collections.Async
命名空间中的 ParallelForEachAsync
扩展方法。
除了最后的完全重新设计之外,我认为强调原始代码的真正错误是非常重要的。
0) 首先,正如@Serge Semenov 立即指出的那样,必须将 Action 替换为
Func<Task>
但还有另外两个本质的变化。
1) 使用异步委托作为参数,有必要使用更新的 Task.Run 而不是旧模式 new TaskFactory.StartNew (否则您必须显式添加 Unwrap() )
2) 此外,ex() 方法不能是异步的,因为 Task.WhenAll 必须使用 Wait() 等待,而不需要等待。
到那时,即使有需要重新设计的逻辑错误,从纯技术的角度来看,它确实有效并产生了输出。
可以在线进行测试:http://rextester.com/HMMI93124
我想编写一个接受多个参数的方法,包括一个动作和一个重试次数并调用它。
所以我有这个代码:
public static IEnumerable<Task> RunWithRetries<T>(List<T> source, int threads, Func<T, Task<bool>> action, int retries, string method)
{
object lockObj = new object();
int index = 0;
return new Action(async () =>
{
while (true)
{
T item;
lock (lockObj)
{
if (index < source.Count)
{
item = source[index];
index++;
}
else
break;
}
int retry = retries;
while (retry > 0)
{
try
{
bool res = await action(item);
if (res)
retry = -1;
else
//sleep if not success..
Thread.Sleep(200);
}
catch (Exception e)
{
LoggerAgent.LogException(e, method);
}
finally
{
retry--;
}
}
}
}).RunParallel(threads);
}
RunParallel 是 Action 的扩展方法,它看起来像这样:
public static IEnumerable<Task> RunParallel(this Action action, int amount)
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < amount; i++)
{
Task task = Task.Factory.StartNew(action);
tasks.Add(task);
}
return tasks;
}
现在,问题是:线程正在消失或崩溃,而没有等待操作完成。
我写了这个示例代码:
private static async Task ex()
{
List<int> ints = new List<int>();
for (int i = 0; i < 1000; i++)
{
ints.Add(i);
}
var tasks = RetryComponent.RunWithRetries(ints, 100, async (num) =>
{
try
{
List<string> test = await fetchSmthFromDb();
Console.WriteLine("#" + num + " " + test[0]);
return test[0] == "test";
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
return false;
}
}, 5, "test");
await Task.WhenAll(tasks);
}
fetchSmthFromDb
是一个简单的任务>,它从数据库中获取一些东西,并且在这个例子之外调用时工作得很好。
每当调用 List<string> test = await fetchSmthFromDb();
行时,线程似乎正在关闭并且 Console.WriteLine("#" + num + " " + test[0]);
甚至没有被触发,调试断点时也从未命中。
最终工作代码
private static async Task DoWithRetries(Func<Task> action, int retryCount, string method)
{
while (true)
{
try
{
await action();
break;
}
catch (Exception e)
{
LoggerAgent.LogException(e, method);
}
if (retryCount <= 0)
break;
retryCount--;
await Task.Delay(200);
};
}
public static async Task RunWithRetries<T>(List<T> source, int threads, Func<T, Task<bool>> action, int retries, string method)
{
Func<T, Task> newAction = async (item) =>
{
await DoWithRetries(async ()=>
{
await action(item);
}, retries, method);
};
await source.ParallelForEachAsync(newAction, threads);
}
问题出在这一行:
return new Action(async () => ...
您使用异步 lambda 启动异步操作,但没有 return 等待的任务。 IE。它 运行 在工作线程上运行,但您永远不会知道它何时完成。并且您的程序在异步操作完成之前终止 - 这就是您看不到任何输出的原因。
需要:
return new Func<Task>(async () => ...
更新
首先,您需要拆分方法的职责,因此不要将重试策略(不应硬编码为检查布尔结果)与 运行ning 任务并行。
然后,如前所述,您 运行 您的 while (true)
循环 100 次,而不是并行处理。
正如@MachineLearning 指出的那样,使用 Task.Delay
而不是 Thread.Sleep
。
总体而言,您的解决方案如下所示:
using System.Collections.Async;
static async Task DoWithRetries(Func<Task> action, int retryCount, string method)
{
while (true)
{
try
{
await action();
break;
}
catch (Exception e)
{
LoggerAgent.LogException(e, method);
}
if (retryCount <= 0)
break;
retryCount--;
await Task.Delay(millisecondsDelay: 200);
};
}
static async Task Example()
{
List<int> ints = new List<int>();
for (int i = 0; i < 1000; i++)
ints.Add(i);
Func<int, Task> actionOnItem =
async item =>
{
await DoWithRetries(async () =>
{
List<string> test = await fetchSmthFromDb();
Console.WriteLine("#" + item + " " + test[0]);
if (test[0] != "test")
throw new InvalidOperationException("unexpected result"); // will be re-tried
},
retryCount: 5,
method: "test");
};
await ints.ParallelForEachAsync(actionOnItem, maxDegreeOfParalellism: 100);
}
您需要使用 AsyncEnumerator NuGet Package 才能使用 System.Collections.Async
命名空间中的 ParallelForEachAsync
扩展方法。
除了最后的完全重新设计之外,我认为强调原始代码的真正错误是非常重要的。
0) 首先,正如@Serge Semenov 立即指出的那样,必须将 Action 替换为
Func<Task>
但还有另外两个本质的变化。
1) 使用异步委托作为参数,有必要使用更新的 Task.Run 而不是旧模式 new TaskFactory.StartNew (否则您必须显式添加 Unwrap() )
2) 此外,ex() 方法不能是异步的,因为 Task.WhenAll 必须使用 Wait() 等待,而不需要等待。
到那时,即使有需要重新设计的逻辑错误,从纯技术的角度来看,它确实有效并产生了输出。
可以在线进行测试:http://rextester.com/HMMI93124