/// <summary>
        /// Executes when the async operation is completed.
        ///
        /// Set the global context and then call the RunWorkerCompleted
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
        private void InternalRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Exception error  = null;
            object    result = null;

            if (!e.Cancelled)
            {
                var workerResult = (WorkerAsyncResult)e.Result;
                // always set GlobalContext returned in the BW
                // so it can be addressed in RunWorkerCompleted.
                GlobalContext = workerResult.GlobalContext;

                // must check for error as accessing e.Result will throw exception
                // if e.Error is not null.
                error = workerResult.Error;
                if (workerResult.Error == null)
                {
                    result = workerResult.Result;
                }
            }


            if (_myWorkerCompleted != null)
            {
                _myWorkerCompleted.Invoke(this, new RunWorkerCompletedEventArgs(result, error, e.Cancelled));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     研究機関ファイル群を遅延読み込みする
        /// </summary>
        /// <param name="handler">読み込み完了イベントハンドラ</param>
        public static void LoadAsync(RunWorkerCompletedEventHandler handler)
        {
            // 既に読み込み済みならば完了イベントハンドラを呼び出す
            if (_loaded)
            {
                handler?.Invoke(null, new RunWorkerCompletedEventArgs(null, null, false));
                return;
            }

            // 読み込み完了イベントハンドラを登録する
            if (handler != null)
            {
                Worker.RunWorkerCompleted += handler;
                Worker.RunWorkerCompleted += OnWorkerRunWorkerCompleted;
            }

            // 読み込み途中ならば戻る
            if (Worker.IsBusy)
            {
                return;
            }

            // ここで読み込み済みならば既に完了イベントハンドラを呼び出しているので何もせずに戻る
            if (_loaded)
            {
                return;
            }

            // 遅延読み込みを開始する
            Worker.DoWork += OnWorkerDoWork;
            Worker.RunWorkerAsync();
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     マップファイルを遅延読み込みする
        /// </summary>
        /// <param name="level">マップレベル</param>
        /// <param name="handler">読み込み完了イベントハンドラ</param>
        public static void LoadAsync(MapLevel level, RunWorkerCompletedEventHandler handler)
        {
            // 読み込み禁止ならば何もしない
            if (ForbidLoad)
            {
                return;
            }

            // 既に読み込み済みならば完了イベントハンドラを呼び出す
            if (IsLoaded[(int)level])
            {
                handler?.Invoke(null, new RunWorkerCompletedEventArgs(level, null, false));
                return;
            }

            // 読み込み完了イベントハンドラを登録する
            BackgroundWorker worker = Workers[(int)level];

            if (handler != null)
            {
                worker.RunWorkerCompleted += handler;
                worker.RunWorkerCompleted += OnMapWorkerRunWorkerCompleted;
            }

            // 読み込み途中ならば戻る
            if (worker.IsBusy)
            {
                return;
            }

            // ここで読み込み済みならば既に完了イベントハンドラを呼び出しているので何もせずに戻る
            if (IsLoaded[(int)level])
            {
                return;
            }

            // 遅延読み込みを開始する
            worker.DoWork += MapWorkerDoWork;
            worker.RunWorkerAsync(level);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Redownload files with given relative filenames.
        /// </summary>
        /// <param name="stepReport">This method will be invoked everytime the download proceed to tell the filename. This is thread-safe invoke.</param>
        /// <param name="downloadprogressReport">This method will be invoked everytime the download proceed. This is thread-safe invoke.</param>
        /// <param name="downloadFinished_CallBack">This method will be invoked when the download is finished. This is thread-safe invoke.</param>
        /// <returns>Bool. True if the download is succeeded, otherwise false.</returns>
        public static bool RedownloadFiles(ExtendedWebClient _webClient, Dictionary <string, string> fileList, EventHandler <StringEventArgs> stepReport, Func <int, int, bool> downloadprogressReport, RunWorkerCompletedEventHandler downloadFinished_CallBack)
        {
            bool      continueDownload = true;
            Exception Myex             = null;
            int       filecount        = 0;
            Uri       currenturl       = null;
            var       asdasdads        = _webClient.CacheStorage;

            _webClient.CacheStorage = null;
            List <string> failedfiles = new List <string>();

            try
            {
                HttpStatusCode lastCode;
                byte[]         buffer = new byte[1024];
                //long byteprocessed, filelength;
                foreach (var _keypair in fileList)
                {
                    if (stepReport != null)
                    {
                        WebClientPool.SynchronizationContext.Send(new System.Threading.SendOrPostCallback(delegate { stepReport.Invoke(_webClient, new StringEventArgs(_keypair.Key)); }), null);
                    }
                    using (FileStream local = File.Create(_keypair.Value, 1024))
                    {
                        var _pso22fileurl = new PSO2FileUrl(Leayal.UriHelper.URLConcat(DefaultValues.Web.MainDownloadLink, _keypair.Key), Leayal.UriHelper.URLConcat(DefaultValues.Web.OldDownloadLink, _keypair.Key));
                        currenturl = _pso22fileurl.MainUrl;
                        lastCode   = HttpStatusCode.ServiceUnavailable;
                        //byteprocessed = 0;
                        //filelength = 0;
                        try
                        {
                            using (HttpWebResponse theRep = _webClient.Open(currenturl) as HttpWebResponse)
                            {
                                if (theRep.StatusCode == HttpStatusCode.NotFound)
                                {
                                    throw new WebException("File not found", null, WebExceptionStatus.ReceiveFailure, theRep);
                                }
                                else if (theRep.StatusCode == HttpStatusCode.Forbidden)
                                {
                                    throw new WebException("Access denied", null, WebExceptionStatus.ReceiveFailure, theRep);
                                }

                                /*if (theRep.ContentLength > 0)
                                 *  filelength = theRep.ContentLength;
                                 * else
                                 * {
                                 *  HttpWebRequest headReq = _webClient.CreateRequest(currenturl, "HEAD") as HttpWebRequest;
                                 *  headReq.AutomaticDecompression = DecompressionMethods.None;
                                 *  HttpWebResponse headRep = headReq.GetResponse() as HttpWebResponse;
                                 *  if (headRep != null)
                                 *  {
                                 *      if (headRep.ContentLength > 0)
                                 *          filelength = headRep.ContentLength;
                                 *      headRep.Close();
                                 *  }
                                 * }*/
                                using (var theRepStream = theRep.GetResponseStream())
                                {
                                    int count = theRepStream.Read(buffer, 0, buffer.Length);
                                    while (count > 0)
                                    {
                                        local.Write(buffer, 0, count);
                                        //byteprocessed += count;
                                        count = theRepStream.Read(buffer, 0, buffer.Length);
                                    }
                                }
                            }
                        }
                        catch (WebException webEx)
                        {
                            if (webEx.Response != null)
                            {
                                HttpWebResponse rep = webEx.Response as HttpWebResponse;
                                lastCode = rep.StatusCode;
                            }
                        }
                        if (lastCode == HttpStatusCode.NotFound)
                        {
                            currenturl = _pso22fileurl.GetTheOtherOne(currenturl.OriginalString);
                            try
                            {
                                using (HttpWebResponse theRep = _webClient.Open(currenturl) as HttpWebResponse)
                                {
                                    if (theRep.StatusCode == HttpStatusCode.NotFound)
                                    {
                                        throw new WebException("File not found", null, WebExceptionStatus.ReceiveFailure, theRep);
                                    }
                                    else if (theRep.StatusCode == HttpStatusCode.Forbidden)
                                    {
                                        throw new WebException("Access denied", null, WebExceptionStatus.ReceiveFailure, theRep);
                                    }

                                    /*if (theRep.ContentLength > 0)
                                     *  filelength = theRep.ContentLength;
                                     * else
                                     * {
                                     *  HttpWebRequest headReq = _webClient.CreateRequest(currenturl, "HEAD") as HttpWebRequest;
                                     *  headReq.AutomaticDecompression = DecompressionMethods.None;
                                     *  HttpWebResponse headRep = headReq.GetResponse() as HttpWebResponse;
                                     *  if (headRep != null)
                                     *  {
                                     *      if (headRep.ContentLength > 0)
                                     *          filelength = headRep.ContentLength;
                                     *      headRep.Close();
                                     *  }
                                     * }*/
                                    using (var theRepStream = theRep.GetResponseStream())
                                    {
                                        int count = theRepStream.Read(buffer, 0, buffer.Length);
                                        while (count > 0)
                                        {
                                            local.Write(buffer, 0, count);
                                            //byteprocessed += count;
                                            count = theRepStream.Read(buffer, 0, buffer.Length);
                                        }
                                    }
                                }
                            }
                            catch (WebException webEx)
                            {
                                if (webEx.Response != null)
                                {
                                    HttpWebResponse rep = webEx.Response as HttpWebResponse;
                                    if (rep.StatusCode != HttpStatusCode.NotFound)
                                    {
                                        failedfiles.Add(_keypair.Key);
                                    }
                                }
                            }
                        }
                        else
                        {
                            failedfiles.Add(_keypair.Key);
                        }
                    }
                    //fileList[filecount].IndexOfAny(' ');
                    if (downloadprogressReport != null)
                    {
                        WebClientPool.SynchronizationContext.Send(new System.Threading.SendOrPostCallback(delegate { continueDownload = downloadprogressReport.Invoke(filecount, fileList.Count); }), null);
                    }
                    filecount++;
                }
            }
            catch (Exception ex)
            { Myex = ex; }
            _webClient.CacheStorage = asdasdads;
            var myevent = new RunWorkerCompletedEventArgs(failedfiles, Myex, !continueDownload);

            if (downloadFinished_CallBack != null)
            {
                WebClientPool.SynchronizationContext.Post(new System.Threading.SendOrPostCallback(delegate { downloadFinished_CallBack.Invoke(_webClient, myevent); }), null);
            }

            if (myevent.Error != null && !myevent.Cancelled)
            {
                if (failedfiles.Count == 0)
                {
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Raises the <see cref="RunWorkerCompleted"/> event.
        /// </summary>
        /// <param name="e">The <see cref="EventArgs"/> containing data for the event.</param>
        protected virtual void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
        {
            RunWorkerCompletedEventHandler handler = RunWorkerCompleted;

            handler?.Invoke(this, e);
        }