简体   繁体   English

通用参数数目可变的C#方法

[英]c# method with variable number of generic parameters

I'm trying to work with ebay Api, They say you should only at max 18 threads for processing requests + Handle retries. 我正在尝试与ebay Api合作,他们说您最多只能使用18个线程来处理请求+处理重试。

So I'm trying to make a wrapper that will execute all my ebay commands. 所以我试图做一个包装,将执行我所有的ebay命令。

the problem is that I have a lot of different types of requests to ebay, with different number of parameters, So I'm trying to understand how to send them all to my wrapper and get the result I need. 问题是我对ebay的请求类型很多,具有不同数量的参数,所以我试图了解如何将它们全部发送到包装器并获得所需的结果。

Maybe this is not the best way to accomplish this at all, I'm un certain about how to implement this. 也许这根本不是实现此目标的最佳方法,但我不确定如何实现此目标。

private static SemaphoreSlim sem = new SemaphoreSlim(18);
private static int retryCount = 2;

public static async Task<T> RunTask<T, V>(Func<V, T> ebayAction, V param1)
{
  // Wait the semaphore.
  await sem.WaitAsync();
  int currentRetry = 0;
  for (; ; )
  {
    try
    {
      // If response failed try again.
      return await Task.Run(() => ebayAction(param1));
    }
    catch (Exception e)
    {
      currentRetry++;
      if (currentRetry >= retryCount)
      {
        throw e;
      }
    }
    finally
    {
      sem.Release();
    }
  }
}

Example usage: 用法示例:

private List<ProductData> SearchItems(string keyword)
{
  return EbayApiRequestFactory.Create<EbayFindApiRequest>()
    .SetKeyword(keyword)
    .SetEntriesLimit(100)
    .Execute().Result;
}

List<ProductData> searchProducts = await EbayHandler.RunTask(SearchItems, keyword);

I'd change your wrapper signature as follows: 我将如下更改您的包装器签名:

async Task<TResult> RunTask<TResult>(Func<TResult> ebayAction)

And run it as 并运行为

RunTask(() => SearchItems(keyword));

If you have another method with another number of arguments: 如果您有另一个带有其他数量参数的方法:

RunTask(() => SearchItems(keyword, argument2, argument3));

You can add more overloads if necessary, like: 您可以根据需要添加更多重载,例如:

// some action which does not return result
static async Task RunTask(Action ebayAction)
// some function which is already asynchronous so you don't need
// to wrap it into Task.Run
static async Task<TResult> RunTask<TResult>(Func<Task<TResult>> ebayAction)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM