private void messageTransportWork(object state)
{
var cancelToken = (CancellationToken)state;
while (!cancelToken.IsCancellationRequested)
{
bool sentWaitNotice = false;
//Check to see if we should be waiting
while (DateTime.UtcNow < waitUntil && !cancelToken.IsCancellationRequested)
{
//Check if we've sent notice that we're waiting this time yet or not
// and send notice if not
if (!sentWaitNotice && this.Waiting != null && !cancelToken.IsCancellationRequested)
{
sentWaitNotice = true;
this.Waiting(waitUntil);
}
for (int i = 0; i < 10; i++)
{
if (!cancelToken.IsCancellationRequested)
break;
System.Threading.Thread.Sleep(100);
}
}
C2dmMessage toSend = null;
//if (messages.TryDequeue(out toSend))
try
{
if (cancelToken.IsCancellationRequested || (toSend = messages.Take(cancelToken)) == null) continue;
}
catch (OperationCanceledException)
{
continue;
}
try
{
var result = C2dmMessageTransport.Send(toSend, this.googleAuthToken, this.SenderID, this.ApplicationID);
if (this.MessageSuccess != null)
this.MessageSuccess(result);
//Reset the retry
if (lastRetryAfter.TotalSeconds > 0)
lastRetryAfter = new TimeSpan(0, 0, 0);
}
catch (ServiceUnavailableTransportException suEx)
{
//Enqueue the message again to resend later
QueueMessage(toSend);
//Backoff the last retry timespan + new one
lastRetryAfter += suEx.RetryAfter;
//Set the time to wait until
waitUntil = DateTime.UtcNow + lastRetryAfter;
}
catch (MessageTransportException mtEx)
{
if (this.MessageFailure != null)
this.MessageFailure(mtEx);
}
catch (Exception ex)
{
//TODO: Log Error
}
}
}