简体   繁体   中英

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.

So I'm trying to make a wrapper that will execute all my ebay commands.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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