代码之家  ›  专栏  ›  技术社区  ›  Richard Watts

使用信号量限制时线程被中止异常

  •  0
  • Richard Watts  · 技术社区  · 5 年前

    我有一个线程被中止的问题,这个异常在本文中得到了解决 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());
    

    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);
    }
    
    0 回复  |  直到 5 年前