private void OnConversionProgressChanged(ConversionProgressChangedEventArgs args)
 {
     if (_async != null)
     {
         _async.Post(x => ConversionProgressChanged(this, args), null);
     }
 }
Beispiel #2
0
        private WimMessageResult MessageCallback(WimMessageType messageType, object message, object userData)
        {
            if (messageType == WimMessageType.Process && _abortWrite)
            {
                return(WimMessageResult.Abort);
            }

            switch (messageType)
            {
            case WimMessageType.Process:
                _asyncOp.Post(WriteProcessAsync, message);
                break;

            case WimMessageType.Progress:
                _asyncOp.Post(WriteProgressAsync, message);
                break;

            case WimMessageType.Warning:
                _asyncOp.Post(WriteWarningAsync, message);
                break;

            case WimMessageType.Error:
                _asyncOp.Post(WriteErrorAsync, message);
                break;
            }

            return(WimMessageResult.Success);
        }
        /// <summary>
        /// 核心任务运行
        /// </summary>
        void InnerRun()
        {
            try
            {
                _operation.Post(_ => OnStart(), null);
                RunCore();
            }
            catch (Exception ex)
            {
                Exception = ex;
                _operation.Post(_ => OnFail(), null);
            }
            Success &= Exception == null;
            if (Success)
            {
                _operation.Post(_ => OnDone(), null);
            }
            else
            {
                _operation.Post(_ => OnFail(), null);
            }


            _operation.PostOperationCompleted(_ => OnFinish(), null);
        }
 //send events
 private void SendNewRatesEvent(RateRecord rec, Candle candle)
 {
     if (NewRatesEvent != null)
     {
         _asyncOperation.Post(delegate { NewRatesEvent(rec, candle); }, null);
     }
 }
Beispiel #5
0
 protected Action CreateAsyncOperation(Action operation)
 {
     return(() =>
     {
         m_AsyncOper.Post(x => operation(), null);
     });
 }
 void Connect_Completed(object sender, SocketAsyncEventArgs e)
 {
     ReceiveEventArgs.Completed -= Connect_Completed;
     if (e.SocketError == SocketError.Success)
     {
         ReceiveEventArgs.SetBuffer(RecevieBuff, 0, RecevieBuff.Length);
         SendEventArgs = new SocketAsyncEventArgs();
         SendBuff      = new byte[RecevieBuff.Length];
         SendEventArgs.SetBuffer(SendBuff, 0, SendBuff.Length);
         SendEventArgs.RemoteEndPoint = e.RemoteEndPoint;
         SendEventArgs.Completed     += SendEventArgs_Completed;
         ReceiveEventArgs.Completed  += Receive_Completed;
         socket.ReceiveAsync(ReceiveEventArgs);
         if (onConnect != null)
         {
             asyncOp.Post(result =>
             {
                 onConnect(true);
             }, null);
         }
     }
     else
     {
         if (onConnect != null)
         {
             asyncOp.Post(result =>
             {
                 onConnect(false);
             }, null);
         }
         handleExpression();
     }
 }
Beispiel #7
0
 private void crawl_LinkCrawlCompleted(object sender, LinkCrawlCompletedArgs e)
 {
     if (_asyncOp != null && !_cancelPending)
     {
         var args = new CrawlDaddyProgressChangedEventArgs(e, 1, _asyncOp.UserSuppliedState);
         _asyncOp.Post(_onProgressReportDelegate, args);
     }
 }
Beispiel #8
0
 //Zkratka pro vyvolání údalosti při chybě
 private void CallError(string message)
 {
     State = States.Error;
     operation.Post(new SendOrPostCallback(delegate(object state)
     {
         OnDownloadError?.Invoke(this, message);
     }), null);
 }
Beispiel #9
0
 private void Status(string status, float progress = 0f)
 {
     _ao.Post(o =>
     {
         label1.Text        = status;
         progressBar1.Value = (int)(100 * progress);
     }, null);
 }
Beispiel #10
0
        private void Process()
        {
            try
            {
                if (Info == null)
                {
                    State = Status.GettingHeaders;
                    GetHeaders();
                    aop.Post(delegate { DownloadInfoReceived.Raise(this, EventArgs.Empty); }, null);
                }
                var append    = RemainingRangeStart > 0;
                var bytesRead = 0;
                var buffer    = new byte[2 * 1024];
                State = Status.SendingRequest;
                using (var response = RequestHelper.CreateRequestGetResponse(Info, RemainingRangeStart, BeforeSendingRequest, AfterGettingResponse))
                {
                    State = Status.GettingResponse;
                    using (var responseStream = response.GetResponseStream())
                        using (var file = FileHelper.CheckFile(FullFileName, append))
                        {
                            while (allowDownload && (bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                State = Status.Downloading;
                                file.Write(buffer, 0, bytesRead);
                                TotalBytesReceived += bytesRead;
                                speedBytesTotal    += bytesRead;
                                aop.Post(delegate
                                {
                                    ProgressChanged.Raise(this,
                                                          new ProgressChangedEventArgs(SpeedInBytes, this.Progress, TotalBytesReceived));
                                }, Progress);
                            }
                        }
                }

                if (RemainingRangeStart > Info.Length)
                {
                    throw new Exception("Total bytes received overflows content length");
                }
                if (TotalBytesReceived == Info.Length)
                {
                    State = Status.Completed;
                    DownloadCompleted.Raise(this, EventArgs.Empty);
                }
                else if (!allowDownload)
                {
                    State = Status.Paused;
                }
            }
            catch (Exception ex)
            {
                State = Status.ErrorOccured;
                aop.Post(delegate
                {
                    ErrorOccured.Raise(this, new ErrorEventArgs(ex));
                }, null);
            }
        }
Beispiel #11
0
        private void RaiseCardConnectedEvent(Card connectedLowlevelCard)
        {
            Logger.TraceEvent(TraceEventType.Verbose, 0, "Raising CardConnected event");
            Logger.Flush();

            SendOrPostCallback cb = state => CardConnected(null, new WatcherCardEventArgs(connectedLowlevelCard));

            AsyncOperation.Post(cb, null);
        }
Beispiel #12
0
 private void RaisReceived(object msg)
 {
     _operation.Post(state =>
     {
         if (OnReceived != null && msg != null)
         {
             OnReceived(this, (TSMessage)msg);
         }
     }, null);
 }
Beispiel #13
0
        /// <summary>
        /// Called right before the next item is scanned.
        /// </summary>
        protected void PostBeforeScanItem(string itemName)
        {
            SendOrPostCallback cb = delegate(object args) {
                OnBeforeScanItem((BeforeScanItemEventArgs)args);
            };

            BeforeScanItemEventArgs e = new BeforeScanItemEventArgs(itemName);

            asyncOperation.Post(cb, e);
        }
Beispiel #14
0
 private void OnProgressChanged(string message, int?percent)
 {
     operation.Post(new System.Threading.SendOrPostCallback(delegate(object postState) {
         EventHandler <ProgressMessageEventArgs> h = ProgressChanged;
         if (h != null)
         {
             h(this, new ProgressMessageEventArgs(message, percent));
         }
     }), null);
 }
        private void Validate(string currentIP, AsyncOperation asyncOp)
        {
            if (currentIP == null || currentIP.Trim() == string.Empty)
            {
                throw new ArgumentNullException("currentIP");
            }

            Natsuhime.Events.MessageEventArgs e = null;
            while (true)
            {
                ProxyInfo info = GetProxy();
                if (info == null)
                {
                    break;
                }
                e = new Natsuhime.Events.MessageEventArgs("", string.Format("[校验]{0}:{1}", info.Address, info.Port), "", asyncOp.UserSuppliedState);
                asyncOp.Post(this.onStatusChangeDelegate, e);

                string returnData;
                try
                {
                    returnData = ConnectValidatePage(asyncOp, info);
                }
                catch (Exception ex)
                {
                    returnData = string.Empty;
                }
                if (returnData == string.Empty)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("{0}:{1} - Failed", info.Address, info.Port));

                    e = new Natsuhime.Events.MessageEventArgs("", string.Format("[失败]{0}:{1}", info.Address, info.Port), "", asyncOp.UserSuppliedState);
                    asyncOp.Post(this.onStatusChangeDelegate, e);
                    continue;
                }
                if (currentIP == ProxyUtility.GetCurrentIP_RegexPage(returnData, _ProxyValidateUrlInfo.RegexString))
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("{0}:{1} - Bad", info.Address, info.Port));

                    e = new Natsuhime.Events.MessageEventArgs("", string.Format("[透明]{0}:{1}", info.Address, info.Port), "", asyncOp.UserSuppliedState);
                    asyncOp.Post(this.onStatusChangeDelegate, e);
                    continue;
                }

                Monitor.Enter(_ProxyListOK);
                _ProxyListOK.Add(info);
                Monitor.Exit(_ProxyListOK);
                System.Diagnostics.Debug.WriteLine(string.Format("{0}:{1} - OK", info.Address, info.Port));

                e = new Natsuhime.Events.MessageEventArgs("", string.Format("[成功]{0}:{1}", info.Address, info.Port), "", asyncOp.UserSuppliedState);
                asyncOp.Post(this.onStatusChangeDelegate, e);
            }
        }
Beispiel #16
0
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            _disposables.Dispose();
            _uiAsyncOperation.Post(() => _toolStrip.Items.Clear());

            _isDisposed = true;
        }
Beispiel #17
0
        void UpdateProgress()
        {
            int pr = (int)(TotalBytesReceived * 1d / Size * 100);

            if (TotalProgress != pr)
            {
                TotalProgress = pr;
                if (TotalProgressChanged != null)
                {
                    _aop.Post(state => TotalProgressChanged(this, EventArgs.Empty), null);
                }
            }
        }
Beispiel #18
0
 void checkBestValueChanged(Schedule tour)
 {
     if (best == null || CompareFitValue(best, tour))
     {
         best = tour;
         aop.Post(new System.Threading.SendOrPostCallback(delegate
         {
             if (BestValueChanged != null)
             {
                 BestValueChanged(this, EventArgs.Empty);
             }
         }), null);
         nothingFound = 0;
     }
 }
        // 这个方法提供实际的计算流程.它在worker线程上被执行.
        private void CalculateWorker(
            ref List <ProxyInfo> proxyList,
            AsyncOperation asyncOp)
        {
            _ProxyList   = proxyList;
            _ProxyListOK = new List <ProxyInfo>();
            Exception e = null;

            // 检查taskId是否被取消.因为操作可能已经在之前被预先取消了.
            if (!TaskCanceled(asyncOp.UserSuppliedState))
            {
                try
                {
                    string currentIP = ProxyUtility.GetCurrentIP_RegexPage(ConnectValidatePage(asyncOp, null), _ProxyValidateUrlInfo.RegexString);
                    Natsuhime.Events.MessageEventArgs me = new Natsuhime.Events.MessageEventArgs("", string.Format("[校验]{0}[当前IP]", currentIP), "", asyncOp.UserSuppliedState);
                    asyncOp.Post(this.onStatusChangeDelegate, me);
                    Validate(currentIP, asyncOp);
                }
                catch (Exception ex)
                {
                    e = ex;
                }
            }

            this.CompletionMethod(
                _ProxyListOK,
                e,
                TaskCanceled(asyncOp.UserSuppliedState),
                asyncOp);
        }
Beispiel #20
0
 void NativeImageList_LargeExtensionImageLoaded(object sender, NativeImageListEventArgs e)
 {
     if (_startItem != null && _startItem.Magnet.FileName != null && e.Extension.ToLower() == Path.GetExtension(_startItem.Magnet.FileName).ToLower())
     {
         _ao.Post(o => iconPicture.Image = e.Icon, null);
     }
 }
Beispiel #21
0
        /// <summary>
        /// Listens to data received on the UDP port and transfers the received data packets to the originating thread.
        /// </summary>
        /// <param name="asyncOperation"></param>
        private void Listen(AsyncOperation asyncOperation)
        {
            DataReceivedEventArgs e;
            IPEndPoint            remoteHost = null;

            while (_isListening)
            {
                try
                {
                    byte[] data = _socket.Receive(ref remoteHost);

                    // Check to see if we wanted a specific source and whether data came from there
                    if (_ipAddress == null || (_ipAddress.Equals(remoteHost.Address)))
                    {
                        // Raise the DataReceived event on the calling thread
                        e = new DataReceivedEventArgs(data);
                        asyncOperation.Post(OnDataReceivedDelegate, e);
                    }  // if(_ipAddress == null || (_ipAddress.Equals(remoteHost)))
                }
                catch (Exception ex)
                {
                    // TODO: Add "Completed" event
                    Debug.WriteLine(ex.ToString());
                }
            }  // while(_isListening)
        }
        private void GenerateCode(GenerationParameter parameter, ITemplateEngine templateEngine, string templateName,
                                  ref int genratedCount, ref int errorCount, ref int progressCount, AsyncOperation asyncOp)
        {
            foreach (string modelId in parameter.GenerationObjects.Keys)
            {
                string codeFileNamePath = PathHelper.GetCodeFileNamePath(ConfigManager.GenerationCodeOuputPath,
                                                                         ConfigManager.SettingsSection.Languages[parameter.Settings.Language].Alias,
                                                                         ConfigManager.SettingsSection.TemplateEngines[parameter.Settings.TemplateEngine].Name,
                                                                         ConfigManager.TemplateSection.Templates[templateName].DisplayName, parameter.Settings.Package, modelId);
                PathHelper.CreateCodeFileNamePath(codeFileNamePath);

                foreach (string objId in parameter.GenerationObjects[modelId])
                {
                    IMetaData    modelObject  = ModelManager.GetModelObject(parameter.Models[modelId], objId);
                    TemplateData templateData = TemplateDataBuilder.Build(modelObject, parameter.Settings,
                                                                          templateName, parameter.Models[modelId].Database, modelId);

                    if (templateData == null || !templateEngine.Run(templateData))
                    {
                        errorCount++;
                    }
                    else
                    {
                        genratedCount++;
                    }
                    string currentCodeFileName = templateData == null ? string.Empty : templateData.CodeFileName;

                    var args = new GenerationProgressChangedEventArgs(genratedCount,
                                                                      errorCount, currentCodeFileName, ++progressCount, asyncOp.UserSuppliedState);
                    asyncOp.Post(this.onProgressReportDelegate, args);
                }
            }
        }
Beispiel #23
0
        private void CalculateWorker(int numberToTest, AsyncOperation asyncOp)
        {
            bool      isPrime      = false;
            int       firstDivisor = 1;
            Exception e            = null;

            if (!TaskCanceled(asyncOp.UserSuppliedState))
            {
                try
                {
                    int n = 0;
                    ProgressChangedEventArgs eventArgs = null;
                    while (n < int.MaxValue && !TaskCanceled(asyncOp.UserSuppliedState))
                    {
                        float percentage = (float)n * 100 / int.MaxValue;
                        if ((percentage % 1) > 0.000001)
                        {
                            eventArgs = new CalculatePrimeProgressChangedEventArgs(n, (int)((float)n / (float)numberToTest * 100), asyncOp.UserSuppliedState);
                            asyncOp.Post(this.onProgressReportDelegate, eventArgs);
                            Thread.Sleep(0);
                        }
                        n++;
                    }
                }
                catch (Exception ex)
                {
                    e = ex;
                }
            }

            this.CompletionMethod(numberToTest, firstDivisor, isPrime, e, TaskCanceled(asyncOp.UserSuppliedState), asyncOp);
        }
 public static void Post(this AsyncOperation async, Action ac)
 {
     async?.Post(new SendOrPostCallback(delegate(object state)
     {
         ac.Invoke();
     }), null);
 }
 private void LogMessage(string message)
 {
     if (MessageEvent != null)
     {
         _asyncOperation.Post(delegate { MessageEvent(message); }, null);
     }
 }
Beispiel #26
0
        /// <summary>
        /// 使用 AsyncOperation 来报告进度和增量结果。 这确保了在应用程序模型的适当线程或上下文上调用客户端的事件处理程序
        /// 如果 BuildPrimeNumberList 找到了一个质数,它会将该数作为增量结果报告给 ProgressChanged 事件的客户端事件处理程序
        /// </summary>
        /// <param name="numberToList"></param>
        /// <param name="asyncOp"></param>
        /// <returns></returns>
        private ArrayList BuildPrimeNumberList(int numberToTest, AsyncOperation asyncOp)
        {
            ProgressChangedEventArgs e = null;
            ArrayList primes           = new ArrayList();
            int       firstDivisor;
            int       n = 5;

            //Add the first prime numbers.
            primes.Add(2);
            primes.Add(3);

            // Report to the client that a prime was found.
            while (n < numberToTest && !TaskCanceled(asyncOp.UserSuppliedState))
            {
                if (IsPrime(primes, n, out firstDivisor))
                {
                    e = new CalculatePrimeProgressChangedEventArgs(n, (int)((float)n / (float)numberToTest * 100), asyncOp.UserSuppliedState);

                    //调用进度委托
                    asyncOp.Post(this.onProgressReportDelegate, e);

                    primes.Add(n);

                    Thread.Sleep(0);
                }

                //跳过偶数
                n += 2;
            }

            return(primes);
        }
        /// <summary>
        /// Raises the System.ComponentModel.Custom.Generic.BackgroundWorker.ProgressChanged event.
        /// </summary>
        /// <param name="percentProgress">The percentage, from MinProgress to MaxProgress,
        /// of the background operation that is complete.</param>
        /// <param name="userState">An object to be passed to the
        /// System.ComponentModel.Custom.Generic.BackgroundWorker.ProgressChanged event.</param>
        /// <returns>true, if the System.ComponentModel.Custom.Generic.BackgroundWorker reports progress;
        /// otherwise, false.</returns>
        public bool ReportProgress(int percentProgress, TProgress userState)
        {
            if (!WorkerReportsProgress)
            {
                return(false);
            }
            if (percentProgress < MinProgress)
            {
                percentProgress = MinProgress;
            }
            else if (percentProgress > MaxProgress)
            {
                percentProgress = MaxProgress;
            }
            ProgressChangedEventArgs <TProgress> args = new ProgressChangedEventArgs <TProgress>(percentProgress, userState);

            if (asyncOperation != null)
            {
                asyncOperation.Post(progressReporter, args);
            }
            else
            {
                progressReporter(args);
            }
            return(true);
        }
        /// <summary>
        /// 引发 <see cref="WorkerProgressChanged"/> 事件
        /// </summary>
        /// <param name="e">类型为 <see cref="RunworkEventArgs"/> 的事件参数</param>
        protected virtual void OnWorkerProgressChanged(RunworkEventArgs e)
        {
            if (WorkerProgressChanged == null)
            {
                return;
            }

            if (_operation == null)
            {
                WorkerProgressChanged(this, e);
            }
            else
            {
                _operation.Post(callWorkerProgressChanged, e);
            }
        }
Beispiel #29
0
        private void ReaderThread(object stateInfo)
        {
            while (started)
            {
                // Checks if there is something to read.
                var dataAvailable = view.ReadBoolean(ReadPosition + DATA_AVAILABLE_OFFSET);
                if (dataAvailable)
                {
                    // Checks how many bytes to read.
                    int availableBytes = view.ReadInt32(ReadPosition + DATA_LENGTH_OFFSET);
                    var bytes          = new byte[availableBytes];
                    // Reads the byte array.
                    int read = view.ReadArray <byte>(ReadPosition + DATA_OFFSET, bytes, 0, availableBytes);

                    // Sets the flag used to signal that there aren't available data anymore.
                    view.Write(ReadPosition + DATA_AVAILABLE_OFFSET, false);
                    // Sets the flag used to signal that data has been read.
                    view.Write(ReadPosition + READ_CONFIRM_OFFSET, true);

                    MemoryMappedDataReceivedEventArgs args = new MemoryMappedDataReceivedEventArgs(bytes, read);
                    operation.Post(callback, args);
                }

                Thread.Sleep(500);
            }
        }
Beispiel #30
0
        protected override YahooManaged.Base.DownloadCompletedEventArgs <MarketResult> ConvertDownloadCompletedEventArgs(YahooManaged.Base.DefaultDownloadCompletedEventArgs <MarketResult> e)
        {
            MarketDownloadSettings set = (MarketDownloadSettings)e.Settings;

            if (set.Sectors != null)
            {
                SectorsDownloadCompletedEventArgs args = new SectorsDownloadCompletedEventArgs(e.UserArgs, (SectorResponse)e.Response, set);
                if (AsyncSectorsDownloadCompleted != null)
                {
                    AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(this);
                    asyncOp.Post(new SendOrPostCallback(delegate(object obj) { AsyncSectorsDownloadCompleted(this, (SectorsDownloadCompletedEventArgs)obj); }), args);
                }
                return(args);
            }
            else if (set.Industries != null)
            {
                IndustryDownloadCompletedEventArgs args = new IndustryDownloadCompletedEventArgs(e.UserArgs, (IndustryResponse)e.Response, set);
                if (AsyncIndustriesDownloadCompleted != null)
                {
                    AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(this);
                    asyncOp.Post(new SendOrPostCallback(delegate(object obj) { AsyncIndustriesDownloadCompleted(this, (IndustryDownloadCompletedEventArgs)obj); }), args);
                }
                return(args);
            }
            else
            {
                return(null);
            }
        }