[英]C# how to inherit generic method with differing number of required parameters
[英]c# method with variable number of generic parameters
我正在尝试与ebay Api合作,他们说您最多只能使用18个线程来处理请求+处理重试。
所以我试图做一个包装,将执行我所有的ebay命令。
问题是我对ebay的请求类型很多,具有不同数量的参数,所以我试图了解如何将它们全部发送到包装器并获得所需的结果。
也许这根本不是实现此目标的最佳方法,但我不确定如何实现此目标。
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();
}
}
}
用法示例:
private List<ProductData> SearchItems(string keyword)
{
return EbayApiRequestFactory.Create<EbayFindApiRequest>()
.SetKeyword(keyword)
.SetEntriesLimit(100)
.Execute().Result;
}
List<ProductData> searchProducts = await EbayHandler.RunTask(SearchItems, keyword);
我将如下更改您的包装器签名:
async Task<TResult> RunTask<TResult>(Func<TResult> ebayAction)
并运行为
RunTask(() => SearchItems(keyword));
如果您有另一个带有其他数量参数的方法:
RunTask(() => SearchItems(keyword, argument2, argument3));
您可以根据需要添加更多重载,例如:
// 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.