Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 自托管pushsharp-Events\u OnNotificationSendFailure失败:线程池中没有足够的可用线程来完成操作_Multithreading_Windows Services_Threadpool_Pushsharp - Fatal编程技术网

Multithreading 自托管pushsharp-Events\u OnNotificationSendFailure失败:线程池中没有足够的可用线程来完成操作

Multithreading 自托管pushsharp-Events\u OnNotificationSendFailure失败:线程池中没有足够的可用线程来完成操作,multithreading,windows-services,threadpool,pushsharp,Multithreading,Windows Services,Threadpool,Pushsharp,我的PushSharp服务是在windows服务中自托管的, 但过了一会儿,它总是抛出: 事件通知发送失败 -例外情况是“线程池中没有足够的可用线程来完成操作”正确的方法是什么 public partial class PushNotificationService : ServiceBase { private static bool flagNotification = true; static PushService push; protected overri

我的PushSharp服务是在windows服务中自托管的,
但过了一会儿,它总是抛出:
事件通知发送失败 -例外情况是“线程池中没有足够的可用线程来完成操作”

正确的方法是什么

public partial class PushNotificationService : ServiceBase
{
    private static bool flagNotification = true;
    static PushService push;


    protected override void OnStart(string[] args)
    {
        SetPushService();

        //start console service worker
        Thread t = new Thread(NotificationServiceWorker);
        t.IsBackground = true;
        t.Start();
    }

    private static void NotificationServiceWorker()
    {
        try
        {
            int sendNotificationTimeGap = Convert.ToInt32(ConfigurationManager.AppSettings["SendNotificationTimeGap"]);
            while (flagNotification)
            {
                try
                {
                    /// get IosPushNotificationService
                    IosPushNotificationService pns = new IosPushNotificationService();
                    /// Get The New Notification from db
                    List<NewPushNotifications> notificationToSend = pns.GetIosNotificationsToSend().Where(n => (n.CreatedDate ?? DateTime.Now) > DateTime.Now.AddMinutes(-5)).ToList();


                    if (notificationToSend != null && notificationToSend.Count > 0)
                    {
                        SendNotificationToIphone(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Iphone).ToList());
                        SendNotificationToAndroid(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Android).ToList());
                    }

                    Thread.Sleep(sendNotificationTimeGap);
                }
                catch (Exception ex)
                {
                    CustomError.Error("error in flagNotification loop", ex);
                }
            }
        }
        catch (Exception ex)
        {
            CustomError.Error("error in NotificationServiceWorker", ex);
        }
    }

    private static void SetPushService()
    {
        push = new PushService();

        push.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
        push.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
        push.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
        push.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
        push.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);

        string androidSenderId = ConfigurationManager.AppSettings["AndroidSenderId"];
        string androidSenderAuthToken = ConfigurationManager.AppSettings["AndroidSenderAuthToken"];
        string androidPackage = ConfigurationManager.AppSettings["androidPackage"];


        push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings(androidSenderId, androidSenderAuthToken, androidPackage), new PushSharp.Common.PushServiceSettings() { AutoScaleChannels = false });

        string appleCertificates = ConfigurationManager.AppSettings["AppleCertificates"];
        var appleCert = File.ReadAllBytes(appleCertificates);
        var appleCertPassword = ConfigurationManager.AppSettings["AppleCertPassword"];
        var appleIsProduction = ConfigurationManager.AppSettings["AppleIsProduction"].ToLower() == bool.TrueString;

        push.StartApplePushService(new ApplePushChannelSettings(appleIsProduction, appleCert, appleCertPassword));


    }
公共部分类PushNotificationService:ServiceBase
{
私有静态布尔flagNotification=true;
静态推送服务推送;
启动时受保护的覆盖无效(字符串[]args)
{
SetPushService();
//启动控制台服务人员
线程t=新线程(NotificationServiceWorker);
t、 IsBackground=true;
t、 Start();
}
私有静态void NotificationServiceWorker()
{
尝试
{
int sendNotificationTimeGap=Convert.ToInt32(ConfigurationManager.AppSettings[“sendNotificationTimeGap]”);
while(标记通知)
{
尝试
{
///获取消息通知服务
IosPushNotificationService pns=新的IosPushNotificationService();
///从数据库获取新通知
List notificationToSend=pns.GetIosNotificationsToSend().Where(n=>(n.CreatedDate??DateTime.Now)>DateTime.Now.AddMinutes(-5)).ToList();
if(notificationToSend!=null&¬ificationToSend.Count>0)
{
SendNotificationToPhone(notificationToSend.Where(gn=>gn.deviceType.Value==(int)deviceType.Iphone.ToList());
SendNotificationToAndroid(notificationToSend.Where(gn=>gn.deviceType.Value==(int)deviceType.Android.ToList());
}
线程睡眠(sendNotificationTimeGap);
}
捕获(例外情况除外)
{
错误(“flagNotification循环中的错误”,ex);
}
}
}
捕获(例外情况除外)
{
CustomError.Error(“NotificationServiceWorker中的错误”,例如);
}
}
私有静态void SetPushService()
{
推送=新的推送服务();
push.Events.OnDeviceSubscriptionIdChanged+=新的PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(事件\u OnDeviceSubscriptionIdChanged);
push.Events.OnDeviceSubscriptionExpired+=新的PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events\u OnDeviceSubscriptionExpired);
push.Events.OnChannelException+=新的PushSharp.Common.ChannelEvents.channelexceptionlegate(Events\OnChannelException);
push.Events.OnNotificationSendFailure+=新的PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(事件\u OnNotificationSendFailure);
push.Events.OnNotificationSent+=新的PushSharp.Common.ChannelEvents.NotificationSentDelegate(事件\u OnNotificationSent);
字符串androidSenderId=ConfigurationManager.AppSettings[“androidSenderId”];
字符串AndroidEnderauthToken=ConfigurationManager.AppSettings[“AndroidEnderauthToken”];
字符串androidPackage=ConfigurationManager.AppSettings[“androidPackage”];
push.StartGoogleCloudMessagingPushService(新的GcmPushChannelSettings(AndroidEnderId、AndroidEnderauthToken、androidPackage)、新的PushSharp.Common.PushServiceSettings(){AutoScaleChannel=false});
字符串appleCertificates=ConfigurationManager.AppSettings[“appleCertificates”];
var appleCert=File.ReadAllBytes(appleCertificates);
var appleCertPassword=ConfigurationManager.AppSettings[“appleCertPassword”];
var appleIsProduction=ConfigurationManager.AppSettings[“appleIsProduction”]。ToLower()==bool.TrueString;
push.StartApplePushService(新的ApplePushChannel设置(AppleProduction、appleCert、appleCertPassword));
}

}不要使用线程,你可以像这样使用计时器

protected override void OnStart(string[] args)
    {
        NotificationServiceEventLog.WriteEntry("Service Started at"+DateTime.Now);

        if (oNotificationComponent ==null)
        oNotificationComponent = new NotificationComponent();
标题 私人bool startapplenotification服务(){


你试过调试吗--检查有多少线程池线程,它们在做什么?谢谢,我会试试。这就是你在生产中使用pushsharp的方式吗?我不是.net/c开发者,但这看起来很糟糕
        try
        {

            if (StartAppleNotificationService())
                StartTimer();


        }
        catch (Exception ex)
        {

            NotificationServiceEventLog.WriteEntry(ex.Message);
        }


       base.OnStart(args);
    }
        bool IsStarted = false;
        try
        {

            if (oPushService == null)
            oPushService = new PushService();

            NotificationServiceEventLog.WriteEntry("Apple Notification Service started successfully");
            oPushService.Events.OnChannelCreated += new PushSharp.Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
            oPushService.Events.OnChannelDestroyed += new PushSharp.Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);
            oPushService.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
            oPushService.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
            oPushService.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
            oPushService.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
            oPushService.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);

            byte[] appleCert = File.ReadAllBytes("PushNSCert.p12");
            var settings = new ApplePushChannelSettings(true, appleCert, "123456");
            oPushService.StartApplePushService(settings);

            IsStarted = true;

        }
        catch (Exception ex)
        {

           throw new Exception("Exception in starting Apple Service :" + ex.Message + Environment.NewLine + ex.StackTrace);
        }

        return IsStarted;
    }
    private bool StartTimer() {


        try
        {
            Double Ms = Convert.ToDouble(ConfigurationManager.AppSettings["TickInterval"]);
            NotificationServiceEventLog.WriteEntry("Time Interval" + Ms.ToString());
            MyTimer = new Timer();
            MyTimer.Interval += (1)*(60)*(1000);
            MyTimer.Enabled = true;
            MyTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
        }
        catch (Exception ex) {

            throw ex;

        }
        return true;
    } 
    private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
    {
        string SentNotificationIDz = "";
        try
        {
            MyTimer.Enabled = false;

            string szConnectionString = @"Server=.\SQL2K8;Database=PaychecksDB_Live;User Id=sa;Password=tdsadmin@321";
            //ConfigurationManager.AppSettings["connString"];

            lNotifictaion = oNotificationComponent.GetNotificationsList(szConnectionString);

            foreach (NotificationModel oNotificationModel in lNotifictaion)
            {
                SendNotification(oNotificationModel.DeviceToken, oNotificationModel.NotificationMessage + " (" + oNotificationModel.NotificationTitle + ")");
                if (SentNotificationIDz == null)
                    SentNotificationIDz += oNotificationModel.Oid;
                else
                    SentNotificationIDz += "," + oNotificationModel.Oid;
            }
            oNotificationComponent.DeleteSentNotifications(SentNotificationIDz, szConnectionString);
            MyTimer.Enabled = true;
        }
        catch (Exception ex) {
            throw ex;
        }

      //  
    }
    private void SendNotification(string p_szDeviceToken,string p_szAlert)
    {

        try
        {

            oPushService.QueueNotification(NotificationFactory.Apple()
                                                      .ForDeviceToken(p_szDeviceToken)
                                                      .WithAlert(p_szAlert)
                                                      .WithBadge(2)
                                                      .WithSound("default")
                                                      .WithExpiry(DateTime.Now.AddDays(1))
                                                       );
        }
        catch (Exception ex)
        {
            throw new Exception("Error in sending Push Notification:" + ex.Message + Environment.NewLine + ex.StackTrace);
        }
    }