Skip to content

Instantly share code, notes, and snippets.

@jaredjenkins
Created April 19, 2013 17:53
Show Gist options
  • Save jaredjenkins/5421985 to your computer and use it in GitHub Desktop.
Save jaredjenkins/5421985 to your computer and use it in GitHub Desktop.
Parallel http requests in Unity
private IEnumerator ProcessRequests()
{
if(isProcessing || taskQueue.Count == 0){
yield break;
}
isProcessing = true;
//get a temp variable, otherwise we could be stuck in an infinite-loop (offline scenario)
int itemsToProcess = taskQueue.Count;
while(itemsToProcess > 0){
ApiRequest request = taskQueue.Peek();
if((!request.FutureProcessDate.HasValue) || (request.FutureProcessDate.Value < DateTime.UtcNow))
{
//not need to wait here, so don't yeild return
StartCoroutine( DoRequest(taskQueue.Dequeue()) );
}
itemsToProcess --;
}
isProcessing = false;
}
private IEnumerator DoRequest(ApiRequest request)
{
request.Attempts ++;
Logger.Log(LogType.Log, "Starting Request (Attempt {1}) {0}", request.Url, request.Attempts);
WWW httpRequest = new WWW(request.Url);
//yield control back to the caller so that we're not waiting for the download to complete,
//will resume the call when the web call completes
yield return httpRequest;
if(httpRequest.isDone && string.IsNullOrEmpty(httpRequest.error))
{
if(request.RequestCompleteHandler != null){
request.RequestCompleteHandler(request.Url, httpRequest);
}
LocalCache.instance.UpdateLastEventEpochTime(DateTime.UtcNow);
Logger.Log(LogType.Log, "Request succeeded");
} else {
Logger.Log(LogType.Warning, "Request failed with Error: {0}", httpRequest.error);
if(request.ShouldPersist && request.Attempts < maxRetryCount){
double retryMinutes = Math.Pow((double)futureTaskIncrementMinutes, (double)request.Attempts);
request.FutureProcessDate = DateTime.UtcNow.AddMinutes(retryMinutes);
Logger.Log(LogType.Log, "Request failed, but retrying in {0} minutes.", retryMinutes);
taskQueue.Enqueue(request);
} else {
Logger.Log(LogType.Log, "Request failed, not retrying.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment