【发布时间】:2013-03-26 03:58:13
【问题描述】:
我在我的应用中实现了一些请求限制。它基于使用 MemoryCache 和根据限制过期的项目。基本上我尝试检索一个缓存项,如果它不存在我继续发出请求,如果是他们我检查最后一个请求并锻炼下一个可用时间我可以发出请求。我的问题在于我必须等待提出请求。
//This is a shortened version of what im doing, but the includes the required code
public void ThrottleRequest(string webservice)
{
if (cache.TryGet(webservice))
{
var timeToWait = GetTimeToWaitFromSomewhere();
Wait(timeToWait);
}
}
public async void Wait(TimeSpan timeToWait)
{
await Task.Delay(timeToWait); //This doesnt work
Thread.Sleep(timeToWait); //This works
}
问题在于等待方法。如果我使用 thread.sleep 数字匹配并且请求被正确限制(即每秒 1 个请求),但我永远不想在生产环境中使用它。那么在这里异步等待的正确方法是什么?我是在滥用 API 还是什么?
【问题讨论】:
-
你应该避免
async void。我在MSDN article 中给出了所有原因。
标签: c# asynchronous throttling