首页 > 解决方案 > 使用 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);
}

标签: .netasynchronoussemaphore

解决方案


推荐阅读