.net - 使用 SemaphoreSlim 时线程被中止异常
问题描述
我遇到了 Thread was being aborted 异常问题,在这篇文章中解决了 Thread was being aborted error when making a service call from async method
List<Task> tasks = new List<Task>();
using (var throttler = new SemaphoreSlim(10))
{
foreach (var cust in e.customers)
{
await throttler.WaitAsync();
tasks.Add(Task.Run(() =>
{
try
{
exMan.perfomAction(cust, userId);
}
finally
{
throttler.Release();
}
}));
}
}
Task.WaitAll(tasks.ToArray());
如果我使 exMan.perfomAction 异步并将节流器传递给这样的方法,它就可以工作。我不知道为什么它会干扰异步进程并且这种方法是否有任何缺点?
List<Task> tasks = new List<Task>();
using (var throttler = new SemaphoreSlim(10))
{
foreach (var cust in e.customers)
{
tasks.Add(exMan.perfomAction(cust, userId, throttler));
}
}
Task.WaitAll(tasks.ToArray());
public async Task performAction(Customer customer, string userId, SemaphoreSlim throttler)
{
await throttler.WaitAsync();
//--Do stuff (service calls, DB calls, export to file
throttler.Release();
}
编辑
因此,我进行了两项更改,这些更改似乎有所作为,并且按预期工作。服务调用已异步进行,正在等待。
var axPriceList = await client.findExAsync(callContext, queryCriteria, documentContext);
现在正在等待调用包含以下代码的方法的根调用
private async Task CallingMethod(string cust, string userId)
{
await MehodA(string cust, string userId);
}
private async Task MehodA(string cust, string userId)
{
List<Task> tasks = new List<Task>();
using (var throttler = new SemaphoreSlim(10))
{
foreach (var cust in e.customers)
{
tasks.Add(tasks.Add(Task.Run(async () =>
{
try
{
await exMan.perfomAction(cust, userId);
}
finally
{
throttler.Release();
}
}));
}
}
await Task.WhenAll(tasks);
}
解决方案
推荐阅读
- ssl - log4j2-config.xml 中的 Log4j2 TCP-SSL Appender 配置
- regex - 如何在 x 和 y 中正则表达式搜索 a,并且仅在 x 中找到 a 时才包括替换 y?
- python - 尝试通过 pip 安装 mysql-connector 时出现 Python 错误
- laravel - 验证年龄变量 - Laravel RegisterController
- java - java - 如何定义一个接收两个类型为T的参数的方法,以及在java中扩展T的S?
- reporting-services - Report Builder 3.0 中的 LENGTH 等效项
- linux - perf.data 到文本或 csv
- sql - Postgres 自连接递归 CTE 祖先链
- php - 正确的类加载 PHP
- javascript - 查询 Firebase 数据库以获取过滤列表