internal bool SendMessages() { faulted = false; channel.EnsureConnection(); mre.Reset(); IAsyncResult ar = this.channel.apnsStream.BeginRead(this.readBuffer, 0, 6, new AsyncCallback(OnAsyncRead), null); while (!faulted && current < notifications.Length) { Notification notification = notifications[current]; byte[] notificationBytes = null; try { notificationBytes = notification.ToBytes(); } catch (Exception x) { errors.Add(new NotificationDeliveryError(x, notification)); current++; continue; } try { if (!faulted) { this.channel.apnsStream.Write(notificationBytes); Console.WriteLine("Sent {0}", notification.DeviceToken); current++; } } catch (IOException) { } catch (ObjectDisposedException) { } } if (!ar.IsCompleted) { // Give Apple a chance to let us know something went wrong ar.AsyncWaitHandle.WaitOne(500); if (!ar.IsCompleted) { // Dispose the channel, which will force the async callback, // resulting in an ObjectDisposedException on EndRead. channel.apnsStream.Dispose(); } } mre.WaitOne(); return(!faulted); }
private void workerMethod() { while (!disposing && !closing) { try { while (this.notifications.Count > 0 && !disposing) { Notification notification = this.notifications.Dequeue(); int tries = 0; bool sent = false; while (!sent && tries < this.SendRetries) { try { if (!disposing) { apnsChannel.EnsureConnection(); try { apnsChannel.Send(notification); } catch (BadDeviceTokenException btex) { var onBadDeviceToken = BadDeviceToken; if (onBadDeviceToken != null) { onBadDeviceToken(this, btex); } } catch (NotificationLengthException nlex) { var onNotificationTooLong = NotificationTooLong; if (onNotificationTooLong != null) { onNotificationTooLong(this, nlex); } } var onNotificationSuccess = NotificationSuccess; if (onNotificationSuccess != null) { onNotificationSuccess(this, notification); } sent = true; } else { apnsChannel.ForceReconnect(); } } catch (Exception ex) { var onError = Error; if (onError != null) { onError(this, ex); } apnsChannel.ForceReconnect(); } tries++; } //Didn't send in 3 tries var onNotificationFailed = NotificationFailed; if (!sent && onNotificationFailed != null) { onNotificationFailed(this, notification); } } } catch (Exception ex) { var onError = Error; if (onError != null) { onError(this, ex); } apnsChannel.ForceReconnect(); } if (!disposing) { Thread.Sleep(500); } } }