Beispiel #1
0
 private void CompleteResearch()
 {
     Reward();
     Stop();
     _isCompleted = true;
     OnCompleted?.Invoke(this);
 }
Beispiel #2
0
        private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MainWorker.Dispose();
            MainWorker = null;

            if (Canceled)
            {
                if (InvokeOnPostExecute)
                {
                    OnPostExecute(Result);
                    OnCompleted?.Invoke(Result);
                }
                return;
            }

            OnPostExecute(Result);
            OnCompleted?.Invoke(Result);

            if (methodsToInvokeAfterExecute != null)
            {
                foreach (Tuple <Object, string, object[]> item in methodsToInvokeAfterExecute)
                {
                    item.Item1.GetType().GetMethod(item.Item2)
                    .Invoke(item.Item1, item.Item3);
                }
            }
        }
Beispiel #3
0
 void OnTaskCompleted()
 {
     cancellationTokenSource.Dispose();
     cancellationTokenSource = null;
     HasCompleted            = true;
     OnCompleted?.Invoke(this, EventArgs.Empty);
 }
Beispiel #4
0
        private async void Worker()
        {
            while (isActive)
            {
                var source = await loader.GetSourceByPageId(id); // скачиваем html код страницы

                // в виде строки
                var domParser = new HtmlParser();

                var result = source as T;                        // приводим строку к T
                                                                 // (в данном случае это необязательно)

                OnNewData?.Invoke(this, result);                 // вызываем событие OnNewData

                for (int i = 0; i < 60; i++)                     // задержка
                {
                    if (!isActive)
                    {
                        break;
                    }
                    await Task.Delay(500);
                }
            }
            OnCompleted?.Invoke(this);                           // вызываем событие OnCompleted
        }
Beispiel #5
0
        public static async void SignInAsync(LoginData loginData)
        {
            await Task.Run(() => {
                //При отправке обязательно ЗАШИФРОВАТЬ ПАРОЛЬ по открытому ключу полученным с сервера.

                //Отпарвка post или get запроса к серверу.

                //Имитируем задержку сервера
                Thread.Sleep(3000);

                //Заглушка
                var account = _accounts.Where(x => x.UserName.Equals(loginData.UserName) && x.Password.Equals(loginData.Password));
                if (account.Count() > 0)
                {
                    AppController.LoginInfo = new LoginInfoData()
                    {
                        Login = account.First().UserName
                    };

                    OnCompleted?.Invoke(true, "Success");
                }
                else
                {
                    OnCompleted?.Invoke(false, "Неверный логин или пароль.");
                }
            });
        }
Beispiel #6
0
        async void ToggleAnimation()
        {
            if (IsRunning)
            {
                if (OnStartedAnimation != null)
                {
                    await OnStartedAnimation.Begin();
                }

                ToggleIndicator(IsRunning);

                OnStarted?.Invoke(this, null);
            }
            else
            {
                if (OnCompletedAnimation != null)
                {
                    await OnCompletedAnimation.Begin();
                }

                ToggleIndicator(IsRunning);

                OnCompleted?.Invoke(this, null);
            }

            void ToggleIndicator(bool isRunning)
            {
                IsVisible =
                    _loadingIndicator.IsVisible     =
                        _loadingIndicator.IsRunning =
                            IsRunning;

                Opacity = 1;
            }
        }
Beispiel #7
0
        // Метод контролирует процесс парсинга.
        async void Worker()
        {
            for (int i = parserSettings.StartPoint; i <= parserSettings.EndPoint; i++)
            {
                if (!isActive)
                {
                    // Если работа парсера была остановлена.
                    OnCompleted?.Invoke(this);
                    return;
                }

                // Получает исходный код страницы с индексом из цикла.
                var source = await loader.GetSourceByPage(i);

                var domParser = new HtmlParser();

                // Парсит асинхронно код и получает страницу с которой можно работать.
                var document = await domParser.ParseDocumentAsync(source);

                // Передает парсеру документ и получает спарсенные данные.
                var result = parser.Parse(document);

                // Передает ссылку и результат.
                OnNewData(this, result);
            }

            // Если парсер закончил работу.
            OnCompleted?.Invoke(this);
            isActive = false;
        }
Beispiel #8
0
        private async void Worker()
        {
            for (int i = collectorSettings.StartPoint; i <= collectorSettings.EndPoint; i++)
            {
                if (!isActive)
                {
                    OnCompleted?.Invoke(this);
                    return;
                }

                var source = await loader.GetSourceByPageIdAsync(i);

                var domParser = new HtmlParser();

                var document = await domParser.ParseAsync(source);

                var result = collector.Collect(document);
                //todo: crutch. async bug must be fixed

                OnNewData?.Invoke(this, result);
                Thread.Sleep(10000);
            }

            OnCompleted?.Invoke(this);
            isActive = false;
        }
Beispiel #9
0
        /// <summary>
        /// Загрузить лист событий
        /// </summary>
        /// <returns>Лист событий</returns>
        public List <Event> Parse()
        {
            List <Event> events = new List <Event>();
            // получить html строку
            string html = "";

            try {
                html = GetHtml(url);
            }
            catch {
                return(null);
            }
            // разбить ее на части
            HtmlParser    domParser  = new HtmlParser();
            IHtmlDocument doc        = domParser.Parse(html);
            List <string> htmlEvents = DivideHtml(doc);

            // вытащить из этих частей инф.
            for (int i = 0; i < htmlEvents.Count - 1; i++)
            {
                doc = domParser.Parse(htmlEvents[i]);
                events.Add(GetInfo(doc));
                if (EventLoaded != null)
                {
                    EventLoaded?.Invoke(this, events[i]);
                }
            }
            if (OnCompleted != null)
            {
                OnCompleted?.Invoke(this);
            }

            return(events);
        }
Beispiel #10
0
 /// <summary>
 /// Initializes a new <see cref="AwaitableEvent"/> instance.
 /// </summary>
 /// <param name="handle">The handle to the OpenCL event.</param>
 public AwaitableEvent(IntPtr handle)
     : base(handle, "AwaitableEvent", true)
 {
     // Subscribes to the event callbacks of the OpenCL event, so that a CLR event can be raised
     EventsNativeApi.SetEventCallback(
         Handle,
         (int)CommandExecutionStatus.Queued,
         Marshal.GetFunctionPointerForDelegate(new AwaitableEventCallback((waitEvent, userData) =>
                                                                          OnQueued?.Invoke(this, new EventArgs()))),
         IntPtr.Zero);
     EventsNativeApi.SetEventCallback(
         Handle,
         (int)CommandExecutionStatus.Submitted,
         Marshal.GetFunctionPointerForDelegate(new AwaitableEventCallback((waitEvent, userData) =>
                                                                          OnSubmitted?.Invoke(this, new EventArgs()))),
         IntPtr.Zero);
     EventsNativeApi.SetEventCallback(
         Handle,
         (int)CommandExecutionStatus.Running,
         Marshal.GetFunctionPointerForDelegate(new AwaitableEventCallback((waitEvent, userData) =>
                                                                          OnRunning?.Invoke(this, new EventArgs()))),
         IntPtr.Zero);
     EventsNativeApi.SetEventCallback(
         Handle,
         (int)CommandExecutionStatus.Complete,
         Marshal.GetFunctionPointerForDelegate(new AwaitableEventCallback((waitEvent, userData) =>
                                                                          OnCompleted?.Invoke(this, new EventArgs()))),
         IntPtr.Zero);
 }
Beispiel #11
0
        private async void Worker()
        {
            for (int i = parserSettings.StartPoint; i <= parserSettings.EndPoint; i++)
            {
                if (!isActive)
                {
                    OnCompleted?.Invoke(this);
                    return;
                }


                var source = await loader.GetSourceByPageId(i);

                var domParser = new HtmlParser();


                var document = await domParser.ParseAsync(source);

                var result            = parser.Parse(document);
                var result_Evaluation = parser.Parse_Evaluation(document);
                var result_Price      = parser.Parse_Price(document);
                var result_Advice     = parser.Parse_Advice(document);
                var result_Discount   = parser.Parse_Discount(document);

                OnNewDataName(this, result);
                OnNewDataAdvice(this, result_Advice);
                OnNewDataDiscount(this, result_Discount);
                OnNewDataPrice(this, result_Price);
                OnNewDataEvaluation(this, result_Evaluation);
            }

            OnCompleted?.Invoke(this);
            isActive = false;
        }
Beispiel #12
0
        private async void Worker(string nameShop)
        {
            using (ExcelPackage excel = new ExcelPackage())
            {
                excel.Workbook.Worksheets.Add(nameShop);
                var ExcelWorker = new ExcelWorker();
                int count       = 2;
                for (int i = parserSettings.StartPoint; i <= parserSettings.EndPoint; i++)
                {
                    if (!isActive)
                    {
                        OnCompleted?.Invoke(this);
                        return;
                    }

                    var sourcePage = await loader.GetSourceAsync(_url + i.ToString());

                    var domParser = new HtmlParser();

                    var documentOfPage = await domParser.ParseDocumentAsync(sourcePage);

                    var test = parser.ParseWatch(documentOfPage);
                    ExcelWorker.GenerateDeku(excel, parser.ParseWatch(documentOfPage), count);
                    OnNew?.Invoke(this);
                }
                FileInfo excelFile = new FileInfo(@"C:\Users\Vadim\Desktop\TimeSSS.xlsx");
                excel.SaveAs(excelFile);
                OnCompleted?.Invoke(this);
                isActive = false;
            }
        }
        public void Update()
        {
            if (!_inProgress)
            {
                return;
            }

            _queryBuilder.ForEach((Entity entity, ref TComponent component, ref TMarker marker) =>
            {
                if (_items.ContainsKey(entity))
                {
                    if (component.Completed)
                    {
                        OnItemCompleted?.Invoke(entity, ref component, ref marker);
                        _items.Remove(entity);
                    }
                }
            });
            if (_inProgress && _items.Count == 0)
            {
                _inProgress = false;
                Completed   = true;
                OnCompleted?.Invoke(this);
                OnReadyToRelease?.Invoke(this);
            }
        }
Beispiel #14
0
        private async void Worker()
        {
            if (!isActive)
            {
                OnCompleted?.Invoke(this);
                return;
            }

            try
            {
                var source = await loader.GetSourceByPageId();

                var domParser = new HtmlParser();
                var document  = await domParser.ParseDocumentAsync(source);

                var result = parser.Parse(document);

                OnNewData?.Invoke(this, result);

                IsNetworkError = false;
            }
            catch
            {
                IsNetworkError = true;
            }

            OnCompleted?.Invoke(this);

            isActive = false;
        }
Beispiel #15
0
        //закрытый асинхр метод, который контролирует процесс парсинга
        private async void Worker()
        {
            //прогоняем цикл от стартовой до конечной настроек
            for (int i = parserSetings.StartPoint; i <= parserSetings.EndPoint; i++)
            {
                if (!isActive)
                {
                    //вызов события информирует о конце работы парсера
                    OnCompleted?.Invoke(this);
                    return;
                }
                //получаем исходный код страници с индексом из цикла
                var source = await loader.GetSourceByPageId(i);

                var domParser = new HtmlParser();

                //спарсим асинхронно код и получим док с которым можно работать
                var document = await domParser.ParseAsync(source);

                //передаём док в парсер и записываем в переменную
                var result = parser.Parse(document);

                //вызов события которрое передаёт ссылку и результат
                OnNewData?.Invoke(this, result);
            }

            //вызов события информирует о конце работы парсера
            OnCompleted?.Invoke(this);
            isActive = false;
        }
Beispiel #16
0
        private async void Worker()
        {
            int pageNum = 1;

            while (true)
            {
                if (!isActive)
                {
                    OnCompleted?.Invoke(this);
                    return;
                }

                var source = await loader.GetSourceByPage(pageNum.ToString());

                pageNum = pageNum + 20;
                var domParser = new HtmlParser();

                var document = domParser.ParseDocument(source);

                var result = parser.Parse(document);

                if (result == null)
                {
                    break;
                }
                else
                {
                    OnNewData?.Invoke(this, result);
                }
            }


            OnCompleted?.Invoke(this);
            isActive = false;
        }
Beispiel #17
0
        private IEnumerator RunAnimateProperties(bool toIn)
        {
            // Wait for the delay if the delay isn't being controlled by a tweenable group, and if the delay mode criterium is met.
            if ((IgnoreInTweenableGroup || !IsControlledByTweenableGroup) && Delay > 0 && (DelayMode == DelayModes.Both || DelayMode == DelayModes.InOnly && toIn || DelayMode == DelayModes.OutOnly && !toIn))
            {
                yield return(new WaitForSecondsRealtime(Delay));
            }

            // Init the values to start the interpolation from.
            GetStartingValues(toIn);

            // Determine duratiom.
            float duration = CalculateDuration();

            // Run the animation on all tweenables.
            while (_erpPos < 1)
            {
                SetInterpolation(ApplyEasing(_erpPos), toIn);
                _erpPos = Mathf.MoveTowards(_erpPos, 1, 1f / duration * Time.unscaledDeltaTime);
                yield return(null);
            }

            // Finish at 1.
            SetInterpolation(1, toIn);
            _erpPos = 1;
            // Update the state.
            State = toIn ? TweenableState.In : TweenableState.Out;
            // Alert listeners that the animation completed.
            if (OnCompleted != null)
            {
                OnCompleted.Invoke(toIn);
            }
        }
Beispiel #18
0
 private void RunOnCompleted()
 {
     if (OnCompleted != null)
     {
         OnCompleted.Invoke();
     }
 }
Beispiel #19
0
 public void Reset()
 {
     OnCompleted?.Invoke(this, Status);
     Status = NodeStatus.None;
     StartNode?.Reset();
     Blackboard.Clear();
 }
        /// <summary>
        /// 异步获取Chrome
        /// </summary>
        /// <param name="url">爬虫URL地址</param>
        /// <returns>ChromeDriver</returns>
        public Task <ChromeDriver> GetChromDriver(string url)
        {
            return(Task.Factory.StartNew(() =>
            {
                var driver = new ChromeDriver();
                try
                {
                    OnStart?.Invoke(this, new OnStartEventArgs(url));
                    var watch = new Stopwatch();
                    watch.Start();

                    driver.Url = url;
                    Thread.Sleep(3000);//等待3s


                    var threadId = System.Threading.Thread.CurrentThread.ManagedThreadId; //获取当前任务线程ID
                    var milliseconds = watch.ElapsedMilliseconds;                         //获取请求执行时间
                    OnCompleted?.Invoke(this, new OnCompletedEventArgs(url, threadId, milliseconds, driver));
                }
                catch (Exception ex)
                {
                    OnError?.Invoke(this, new OnErrorEventArgs(url, ex));
                }
                return driver;
            }));
        }
 private void OnCompleteCommandExecute()
 {
     RegistrationSettings.Name   = Name;
     RegistrationSettings.Domain = Domain;
     IsCompleted = true;
     OnCompleted?.Invoke();
 }
 public void Run(Task <TResult> task)
 {
     lock (_lock)
     {
         _lastTask = task;
     }
     task.ContinueWith(t =>
     {
         if (t.IsFaulted)
         {
             throw t.Exception;
         }
         lock (_lock)
         {
             if (_lastTask == task)
             {
                 OnCompleted?.Invoke(t.Result, this);
             }
             else
             {
                 OnDebounced?.Invoke(t.Result, this);
             }
         }
     });
 }
Beispiel #23
0
        /// <summary>
        /// Updates the time of timing by delta time.
        /// </summary>
        /// <param name="deltaTime">The delta time.</param>
        public void Tick(float deltaTime)
        {
            if (TimerState != TimerState.Running)
            {
                return;
            }

            time += deltaTime;
            if (time < Interval)
            {
                return;
            }

            CurrentCount++;

            // Raise Ticking event
            Ticking?.Invoke(this, new TimerTickingEventArgs(CurrentCount));

            if (RepeatCount != 0 && CurrentCount >= RepeatCount)
            {
                Reset();

                OnCompleted?.Invoke(this, EventArgs.Empty);
            }

            time -= Interval;
        }
Beispiel #24
0
    private void HandleInteracted(Interactable targetItem)
    {
        if (requiredEvents.Count > 0)
        {
            foreach (var reqEvent in requiredEvents)
            {
                if (reqEvent.targetEvent.isCompleted != reqEvent.isCompleted)
                {
                    // if one of the requirements is not met, then this current event won't be complete
                    return;
                }
            }
        }

        if (!isCompleted)
        {
            OnCompeleteEvent.Invoke();
            isCompleted = true;
            OnCompleted?.Invoke(this);
        }
        else if (isCompleted && canReset)
        {
            OnResetEvent.Invoke();
            isCompleted = false;
        }
    }
        public AFECustomerChangeNotificationResponse CustomerChange(AFECustomerChangeNotificationRequest request)
        {
            string postdataJson = null;
            var    retval       = new AFECustomerChangeNotificationResponse();

            try
            {
                postdataJson = JsonConvert.SerializeObject(request);
                //var postdataString = new StringContent(postdataJson, new UTF8Encoding(), "application/json");

                var response = _client.PostAsJsonAsync(_targetActionName, request).Result;
                // This extension handles json serialization of the payload etc...

                retval.Success = response.IsSuccessStatusCode;

                OnCompleted?.Invoke($"{_client.BaseAddress.AbsoluteUri}{_targetActionName}",
                                    response.ToString(), postdataJson);
            }
            catch (Exception ex)
            {
                retval.Success = false;
                OnError?.Invoke($"{_client.BaseAddress.AbsoluteUri}{_targetActionName}", ex, postdataJson);
            }

            return(retval);
        }
 public DownloadItem(ImageManager imageManager)
 {
     this.ImageManager  = imageManager;
     this.Requests      = new ConcurrentQueue <DownloadRequest>();
     this.Completed     = new ConcurrentQueue <DownloadResult>();
     this.CancelCommand = ReactiveCommand.Create(Cancel);
     NotificationManager.NotifyInformation($"{imageManager.Title} 다운로드를 시작합니다.");
     ImageManager.Images.ForEachAsync(Environment.ProcessorCount, async item =>
     {
         await Task.Run(() =>
         {
             var obj = new DownloadRequest()
             {
                 Source = item
             };
             obj.Start();
             Requests.Enqueue(obj);
             obj.Subscribe(result => {
                 Completed.Enqueue(result);
                 this.RaisePropertyChanged(nameof(Complection));
                 this.RaisePropertyChanged(nameof(Progress));
                 if (Progress >= 100)
                 {
                     IsCompleted = true;
                     OnCompleted?.Invoke(this, null);
                 }
             });
         });
     });
 }
Beispiel #27
0
    private void OnFinished()
    {
        if (onCompleted != null)
        {
            onCompleted.Invoke();
        }

        holdKeyMinigame.currentHoldTime = 0.0f;

        if (isPlayer1)
        {
            GameCanvas.SetPlayer1Fish(GameCanvas.GetPlayer1Fish() + 1);
        }
        else
        {
            GameCanvas.SetPlayer2Fish(GameCanvas.GetPlayer2Fish() + 1);
        }

        //photonView.RPC("FinishedCall", RpcTarget.AllViaServer);

        //if (isPlayer1)
        //{
        //    photonView.RPC("FinishedCall", RpcTarget.AllViaServer);
        //}
        //else
        //{

        //}

        //myGameObject.SetActive(false);
    }
Beispiel #28
0
        private async void Worker()
        {
            for (int i = parserSettings.StartPoint; i <= parserSettings.EndPoint; i++)
            {
                if (!isActive)
                {
                    OnCompleted?.Invoke(this);
                    return;
                }

                var source = await HTMLoader.GetSourceByPageId(i);

                var domParser = new HtmlParser();

                var document = await domParser.ParseDocumentAsync(ExpandFullPage());



                var result = parser.Parse(document);

                OnNewData?.Invoke(this, result);
            }

            OnCompleted?.Invoke(this);
            isActive = false;
        }
Beispiel #29
0
        private async void Worker()
        {
            for (int i = parserSettings.StartPart; i <= parserSettings.EndPart; i++)
            {
                for (int j = parserSettings.StartArticle; j <= parserSettings.EndArticle; j++)
                {
                    if (!isActive)
                    {
                        OnCompleted?.Invoke(this);
                        return;
                    }

                    var source = await loader.GetSourceByPage(i, j);

                    var domParser = new HtmlParser();

                    var document = await domParser.ParseDocumentAsync(source);

                    var result = parser.Parse(document);

                    OnNewData?.Invoke(this, result);
                }
            }

            OnCompleted?.Invoke(this);
            isActive = false;
        }
Beispiel #30
0
        public static void Pack(DTE2 dte2)
        {
            Dte2 = dte2;

            SolutionPath        = Path.GetDirectoryName(Dte2.Solution.FullName);
            NugetExe            = Path.Combine(SolutionPath, NugetFileName);
            ApiKey              = File.ReadAllText(ApiKeyContainingFile);
            NugetPackagesFolder = Path.Combine(SolutionPath, OutputFolder);

            var start = new System.Threading.ThreadStart(() =>
            {
                try
                {
                    foreach (var item in GetSelectedProjectPath())
                    {
                        PackSingleProject(item);
                    }
                }
                catch (Exception exception)
                {
                    InvokeException(exception);
                }

                OnCompleted?.Invoke(null, EventArgs.Empty);
            });

            Thread = new System.Threading.Thread(start)
            {
                IsBackground = true
            };
            Thread.Start();
        }