コード例 #1
0
ファイル: NetRequester.cs プロジェクト: z3nth10n/uzLib.Lite
        /// <summary>
        ///     Makes a safe request.
        /// </summary>
        /// <param name="safeAction">The safe action.</param>
        /// <param name="continueWithCallback">The continue with callback.</param>
        /// <param name="noInternetCallback">The no internet callback.</param>
        /// <param name="settings">The settings.</param>
        /// <exception cref="ArgumentNullException">
        ///     safeAction
        ///     or
        ///     continueWithCallback
        ///     or
        ///     noInternetCallback
        /// </exception>
        public void MakeSafeRequest(Action safeAction, Action continueWithCallback, Action noInternetCallback,
                                    Action <Settings> frameCallback, Action <bool> retryingConnecion, Settings settings = null)
        {
            if (safeAction == null)
            {
                throw new ArgumentNullException(nameof(safeAction));
            }

            if (continueWithCallback == null)
            {
                throw new ArgumentNullException(nameof(continueWithCallback));
            }

            if (noInternetCallback == null)
            {
                throw new ArgumentNullException(nameof(noInternetCallback));
            }

            if (settings == null)
            {
                settings = Settings.CreateDef();
            }

            try
            {
                safeAction();
            }
            catch (WebException)
            {
                var noInternet = !NetHelper.CheckForInternetConnection();
                do
                {
                    Thread.Sleep(settings.ThreadSleepInterval);

                    var deltaInterval = settings.ThreadSleepInterval / 1000f;
                    settings.m_CurrentTimer += deltaInterval;
                    settings.m_NextRetry    -= deltaInterval;

                    frameCallback?.Invoke(settings);

                    if (settings.m_NextRetry <= 0)
                    {
                        settings.ResetCounter();

                        noInternet = !NetHelper.CheckForInternetConnection();
                        ++settings.m_RetryCount;

                        retryingConnecion?.Invoke(!noInternet);
                    }
                } while (noInternet && settings.m_RetryCount <= settings.MaxRetries);

                if (!noInternet)
                {
                    safeAction();
                }
                else
                {
                    noInternetCallback();
                    return;
                }
            }

            continueWithCallback();
        }