Post() public method

public Post ( SendOrPostCallback d, object arg ) : void
d SendOrPostCallback
arg object
return void
コード例 #1
0
ファイル: BackgroundWorker.cs プロジェクト: pmq20/mono_forked
        public void ReportProgress(int percentProgress, object userState)
        {
            if (!WorkerReportsProgress)
            {
                throw new InvalidOperationException("This background worker does not report progress.");
            }

            if (complete)
            {
                throw new InvalidOperationException("The background worker has ended.");
            }

            ProgressChangedEventArgs pcea = new ProgressChangedEventArgs(percentProgress, userState);

            if (async == null)
            {
                // we can report progress before a call to RunWorkerAsync - but we do it sync
                OnProgressChanged(pcea);
            }
            else
            {
                async.Post(delegate(object o) {
                    ProgressChangedEventArgs e = o as ProgressChangedEventArgs;
                    OnProgressChanged(e);
                }, pcea);
            }
        }
コード例 #2
0
ファイル: MockMdbService.cs プロジェクト: Ejik/chkaddr
        private void IndexerThread(AsyncOperation operation, bool isCreateNewDbFile)
        {
            for (int i = 0; i < 100000; i++)
            {

            }

            SendOrPostCallback callUpdate = delegate(object o)
                                                {
                                                    _view.CloseView();
                                                };
            operation.Post(callUpdate, null); ;
        }
コード例 #3
0
 /// <summary>Raises the <see cref="E:System.ComponentModel.BackgroundWorker.ProgressChanged" /> event.</summary>
 /// <param name="percentProgress">The percentage, from 0 to 100, of the background operation that is complete.</param>
 /// <param name="userState">The state object passed to <see cref="M:System.ComponentModel.BackgroundWorker.RunWorkerAsync(System.Object)" />.</param>
 /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.ComponentModel.BackgroundWorker.WorkerReportsProgress" /> property is set to false. </exception>
 public void ReportProgress(int percentProgress, object userState)
 {
     if (!WorkerReportsProgress)
     {
         throw new InvalidOperationException("This background worker does not report progress.");
     }
     if (IsBusy)
     {
         async.Post(delegate(object o)
         {
             ProgressChangedEventArgs e = o as ProgressChangedEventArgs;
             OnProgressChanged(e);
         }, new ProgressChangedEventArgs(percentProgress, userState));
     }
 }
コード例 #4
0
ファイル: BackgroundWorker.cs プロジェクト: yang73137/corefx
        // Cause progress update to be posted through current AsyncOperation.
        public void ReportProgress(int percentProgress, object userState)
        {
            if (!WorkerReportsProgress)
            {
                throw new InvalidOperationException(SR.BackgroundWorker_WorkerDoesntReportProgress);
            }

            ProgressChangedEventArgs args = new ProgressChangedEventArgs(percentProgress, userState);

            if (_asyncOperation != null)
            {
                _asyncOperation.Post(_progressReporter, args);
            }
            else
            {
                _progressReporter(args);
            }
        }
コード例 #5
0
        /// <summary>
        /// Raises the <see cref="ProgressChanged"/> event.
        /// </summary>
        /// <param name="percentProgress">
        /// The percentage, from 0 to 100, of the background operation that is complete.
        /// </param>
        /// <param name="userState">
        /// The state object passed to <see cref="RunWorkerAsync()"/>.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// The <see cref="WorkerReportsProgress"/> property is <see langword="false"/>.
        /// </exception>
        public void ReportProgress(int percentProgress, object userState)
        {
            if (!WorkerReportsProgress)
            {
                throw new InvalidOperationException();
            }

            ProgressChangedEventArgs e = new ProgressChangedEventArgs(percentProgress, userState);

            if (_currentOperation == null)
            {
                // No operation, just execute it directly
                OnProgressChanged(e);
            }
            else
            {
                // Operation in progress, post it to the synchronization context
                _currentOperation.Post(_ => OnProgressChanged(e), null);
            }
        }
コード例 #6
0
ファイル: Form1.cs プロジェクト: andrewirushkin/skype-sender
        private void send(AsyncOperation operation)
        {
            // в теле этого метода можно обращаться к любому контролу в UI.
            SendOrPostCallback callback = delegate(object state)
            {
                if ((int)state == 10000)
                {
                    button1.Text = "Отправить";
                    return;
                }
                output.Text = String.Concat("Послано " , (int)state);
            };

            SKYPE4COMLib.UserCollection users = skype.Friends;
            List<SKYPE4COMLib.User> friends = new List<SKYPE4COMLib.User>();
            IEnumerator en = users.GetEnumerator();
            while (en.MoveNext())
            {
                friends.Add((SKYPE4COMLib.User)en.Current);
            }
            friends.Sort((x,y)=>x.Handle.CompareTo(y.Handle));
            int count = 0;
            foreach (SKYPE4COMLib.User user in friends)
            {
                if (!continueSend)
                {
                    break;
                }
                if (notOffline)
                {
                    if (user.OnlineStatus != TOnlineStatus.olsOffline)
                    {
                        skype.SendMessage(user.Handle, message);
                        sentTo += user.Handle + " (" + user.FullName + ")\n";
                    }
                }
                else
                {
                    skype.SendMessage(user.Handle, message);
                    sentTo += user.Handle + " (" + user.FullName + ")\n";
                }
                count += 1;
                operation.Post(callback, count);
                if (isDelay)
                {
                    Thread.Sleep(1000);
                }
            }
            operation.Post(callback, 10000);
        }
コード例 #7
0
ファイル: BlobTransfer.cs プロジェクト: ntotten/bob-share
        private void ParallelUploadFile(MyAsyncContext asyncContext, AsyncOperation asyncOp)
        {
            BlobTransferProgressChangedEventArgs eArgs = null;
            object AsyncUpdateLock = new object();

            // stats from azurescope show 10 to be an optimal number of transfer threads
            int numThreads = 10;
            var file = new FileInfo(m_FileName);
            long fileSize = file.Length;

            int maxBlockSize = GetBlockSize(fileSize);
            long bytesUploaded = 0;
            int blockLength = 0;

            // Prepare a queue of blocks to be uploaded. Each queue item is a key-value pair where
            // the 'key' is block id and 'value' is the block length.
            Queue<KeyValuePair<int, int>> queue = new Queue<KeyValuePair<int, int>>();
            List<string> blockList = new List<string>();
            int blockId = 0;
            while (fileSize > 0)
            {
                blockLength = (int)Math.Min(maxBlockSize, fileSize);
                string blockIdString = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("BlockId{0}", blockId.ToString("0000000"))));
                KeyValuePair<int, int> kvp = new KeyValuePair<int, int>(blockId++, blockLength);
                queue.Enqueue(kvp);
                blockList.Add(blockIdString);
                fileSize -= blockLength;
            }

            m_Blob.DeleteIfExists();

            BlobRequestOptions options = new BlobRequestOptions()
            {
                //RetryPolicy = RetryPolicies.RetryExponential(RetryPolicies.DefaultClientRetryCount, RetryPolicies.DefaultMaxBackoff),
                //Timeout = TimeSpan.FromSeconds(90)
            };

            // Launch threads to upload blocks.
            List<Thread> threads = new List<Thread>();

            for (int idxThread = 0; idxThread < numThreads; idxThread++)
            {
                Thread t = new Thread(new ThreadStart(() =>
                {
                    KeyValuePair<int, int> blockIdAndLength;

                    using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
                    {
                        while (true)
                        {
                            // Dequeue block details.
                            lock (queue)
                            {
                                if (asyncContext.IsCancelling)
                                    break;

                                if (queue.Count == 0)
                                    break;

                                blockIdAndLength = queue.Dequeue();
                            }

                            byte[] buff = new byte[blockIdAndLength.Value];
                            BinaryReader br = new BinaryReader(fs);

                            // move the file system reader to the proper position
                            fs.Seek(blockIdAndLength.Key * (long)maxBlockSize, SeekOrigin.Begin);
                            br.Read(buff, 0, blockIdAndLength.Value);

                            // Upload block.
                            string blockName = Convert.ToBase64String(BitConverter.GetBytes(
                                blockIdAndLength.Key));
                            using (MemoryStream ms = new MemoryStream(buff, 0, blockIdAndLength.Value))
                            {
                                string blockIdString = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("BlockId{0}", blockIdAndLength.Key.ToString("0000000"))));
                                string blockHash = GetMD5HashFromStream(buff);
                                m_Blob.PutBlock(blockIdString, ms, blockHash, options: options);
                            }

                            lock (AsyncUpdateLock)
                            {
                                bytesUploaded += blockIdAndLength.Value;

                                int progress = (int)((double)bytesUploaded / file.Length * 100);

                                // raise the progress changed event
                                eArgs = new BlobTransferProgressChangedEventArgs(bytesUploaded, file.Length, progress, CalculateSpeed(bytesUploaded), null);
                                asyncOp.Post(delegate(object e) { OnTaskProgressChanged((BlobTransferProgressChangedEventArgs)e); }, eArgs);
                            }
                        }
                    }
                }));
                t.Start();
                threads.Add(t);
            }

            // Wait for all threads to complete uploading data.
            foreach (Thread t in threads)
            {
                t.Join();
            }

            if (!asyncContext.IsCancelling)
            {
                // Commit the blocklist.
                m_Blob.PutBlockList(blockList, options: options);
            }
        }
コード例 #8
0
ファイル: ProxyValidater.cs プロジェクト: Vinna/DeepInSummer
        // 这个方法提供实际的计算流程.它在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);
        }
コード例 #9
0
        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);
                }
            }
        }
コード例 #10
0
        private void processFieldWorker(string filePath, IProcessingSettings settings,
            AsyncOperation asyncOp)
        {
            Exception e = null;

            Task task = new Task();
            try
            {
                if (settings is TextFieldProcessingSettings)
                {
                    task = _syncClient.ProcessTextField(filePath, settings as TextFieldProcessingSettings);
                }
                else if (settings is BarcodeFieldProcessingSettings)
                {
                    task = _syncClient.ProcessBarcodeField(filePath, settings as BarcodeFieldProcessingSettings);
                }
                else if (settings is CheckmarkFieldProcessingSettings)
                {
                    task = _syncClient.ProcessCheckmarkField(filePath, settings as CheckmarkFieldProcessingSettings);
                }
                else
                {
                    throw new ArgumentException("Invalid type of processing settings");
                }

                // Notify that upload was completed
                Task uploadedTask = new Task(task.Id, TaskStatus.Submitted);
                UploadCompletedEventArgs uploadCompletedEventArgs = new UploadCompletedEventArgs(uploadedTask, asyncOp.UserSuppliedState);
                asyncOp.Post(onUploadCompletedDelegate, uploadCompletedEventArgs);

                // Wait until task finishes
                startTaskMonitorIfNecessary();

                _taskList.AddTask(task);
                task = waitUntilTaskFinishes(task);
            }
            catch (Exception ex)
            {
                e = ex;
            }

            lock (processJobs)
            {
                processJobs.Remove(asyncOp.UserSuppliedState);
            }

            bool canceled = false;

            // Package the results of the operation in EventArgs
            TaskEventArgs ev = new TaskEventArgs(task, e, canceled, asyncOp.UserSuppliedState);

            // End the task. The asyncOp object is responsible 
            // for marshaling the call.
            asyncOp.PostOperationCompleted(onProcessingCompleteDelegate, ev);
        }
コード例 #11
0
ファイル: Task.cs プロジェクト: emret/AsyncSample
        private void MyTaskWorker(string[] files, AsyncOperation async, MyAsyncContext asyncContext, out bool cancelled)
        {
            cancelled = false;

            for (int i = 0; i < files.Length; i++)
            {
                // a time consuming operation with a file (compression, encryption etc.)
                Thread.Sleep(1000);

                // compute progress
                int progressPercentage = 100 * (i + 1) / files.Length;

                // raise the progress changed event
                MyTaskProgressChangedEventArgs eArgs = new MyTaskProgressChangedEventArgs(progressPercentage, files[i], Id, null);
                async.Post(delegate(object e) { OnMyTaskProgressChanged((MyTaskProgressChangedEventArgs)e); }, eArgs);

                if (asyncContext.IsCancelling)
                {
                    cancelled = true;
                    return;
                }
            }
        }
コード例 #12
0
 /// <summary>
 /// Потоковая функция приема данных сенсоров
 /// </summary>
 /// <param name="operation"></param>
 private void SensorLiveScanProcedure(AsyncOperation operation)
 {
     lock (this)
     {
         try
         {
             while (_flagIsScanning)
             {
                 byte[] frame = _consult.GetFrame();
                 operation.Post(DataUpdate, frame);
             }
         }
         finally
         {
             try
             {
                 _consult.ECUFrameStop();
                 _consult.SetClassState(ConsultClassState.ECU_IDLE);
             }
             catch (Exception) { }
         }
     }
 }
コード例 #13
0
 private void RefreshWeaveDataProgressUpdateMethod(string message, AsyncOperation asyncOperation)
 {
     RefreshWeaveDataProgressChangedEventArgs e = new RefreshWeaveDataProgressChangedEventArgs(message, asyncOperation.UserSuppliedState);
     asyncOperation.Post(state => OnProgressChanged((RefreshWeaveDataProgressChangedEventArgs)state), e);
 }
コード例 #14
0
 private void postProgressChanged(AsyncOperation asyncOp, ProgressData progress)
 {
     if ((asyncOp != null) && progress.TotalBytesToSend > 0)
     {
         var _pct = (int)((progress.BytesSent * 100) / progress.TotalBytesToSend);
         asyncOp.Post(this.m_UploadProgressChanged, new UploadFileProgressEventArgs(_pct, asyncOp.UserSuppliedState, progress.BytesSent, progress.TotalBytesToSend));
     }
 }
コード例 #15
0
ファイル: DumpSaver.cs プロジェクト: SayHalou/ospy
        private void DoSave(SaveInfo info, AsyncOperation asyncOp)
        {
            BinaryWriter binWriter = new BinaryWriter(info.m_stream, Encoding.ASCII);

            char[] magic = "oSpy".ToCharArray();
            uint version = 2;
            uint isCompressed = (info.m_format == DumpFormat.Compressed) ? 1U : 0U;
            uint numEvents = (uint)info.m_dump.Events.Count;

            binWriter.Write(magic);
            binWriter.Write(version);
            binWriter.Write(isCompressed);
            binWriter.Write(numEvents);
            binWriter.Flush();
            binWriter = null;

            Stream stream = info.m_stream;
            if (info.m_format == DumpFormat.Compressed)
                stream = new BZip2OutputStream(stream);
            XmlTextWriter xmlWriter = new XmlTextWriter(stream, Encoding.UTF8);
            xmlWriter.WriteStartDocument(true);
            xmlWriter.WriteStartElement("events");

            int eventCount = 0;
            foreach (Event ev in info.m_dump.Events.Values)
            {
                if (asyncOp != null)
                {
                    int pctComplete = (int)(((float)(eventCount + 1) / (float)numEvents) * 100.0f);
                    ProgressChangedEventArgs e = new ProgressChangedEventArgs(pctComplete, asyncOp.UserSuppliedState);
                    asyncOp.Post(m_onProgressReportDelegate, e);
                }

                xmlWriter.WriteRaw(ev.RawData);

                eventCount++;
            }

            xmlWriter.WriteEndElement();
            xmlWriter.Flush();
            stream.Close();
        }
コード例 #16
0
        private void ProcessWorker(Queue<KeyValuePair<string, string>> taskQueue, IEnumerable<IProcessingPlugin> processingPlugins, IOutputPlugin outputPlugin, AsyncOperation asyncOp)
        {
            var imageProcessingManagerTaskContext = new ImageProcessingManagerTaskContext(taskQueue, asyncOp.UserSuppliedState);
            imageProcessingManagerTaskContext.TotalTaskCount = taskQueue.Count;

            lock ((userStateToTaskContext as ICollection).SyncRoot)
            {
                userStateToTaskContext[asyncOp.UserSuppliedState] = imageProcessingManagerTaskContext;
            }

            while (imageProcessingManagerTaskContext.TaskQueue.Count > 0)
            {
                imageProcessingManagerTaskContext.Semaphore.WaitOne();

                if (IsTaskCancelled(asyncOp.UserSuppliedState))
                {
                    break;
                }
                else
                {
                    var task = taskQueue.Dequeue();
                    asyncOp.Post(processAsyncStateChangedDelegate, new ProcessStateChangedEventArgs(asyncOp.UserSuppliedState, task.Key, "处理中"));
                    object userState = Guid.NewGuid();
                    lock ((imageProcessorUserStateToUserState as ICollection).SyncRoot)
                    {
                        imageProcessorUserStateToUserState[userState] = asyncOp.UserSuppliedState;
                    }
                    lock ((imageProcessorUserStateToInput as ICollection).SyncRoot)
                    {
                        imageProcessorUserStateToInput[userState] = task.Key;
                    }
                    lock (imageProcessingManagerTaskContext.CurrentProcessingPluginUserStates)
                    {
                        imageProcessingManagerTaskContext.CurrentProcessingPluginUserStates.Add(userState);
                    }
                    imageProcessor.ProcessAsync(task, processingPlugins, outputPlugin, userState);
                }
            }
            while (imageProcessingManagerTaskContext.CurrentProcessingPluginUserStates.Count > 0)
            {
                imageProcessingManagerTaskContext.Semaphore.WaitOne();
            }
            bool cancelled = IsTaskCancelled(asyncOp.UserSuppliedState);
            asyncOp.PostOperationCompleted(processAsyncCompletedDelegate, new AsyncCompletedEventArgs(null, cancelled, asyncOp.UserSuppliedState));
        }
コード例 #17
0
ファイル: FlockOfBirds.cs プロジェクト: rpavlik/chromium
        private void run(AsyncOperation AsyncOp, SendOrPostCallback OnPoseCallback,
      SendOrPostCallback OnStatusCallback)
        {
            while (!_StopRequest)
            if (!_paused && Bird.FrameReady(GROUP_ID)) {

              // Get data frame from bird
              Bird.Frame frame;
              if(!Bird.GetFrame(GROUP_ID, out frame)) {
            string err = Bird.GetErrorMessage();
            OnStatus(new StatusEventArgs(err));
              }

              Bird.Reading reading = frame.reading[0];

              // convert position and angle data
              Vector3 p = new Vector3(
            (reading.position.X * _PosScale / 32767.0) * 2.54,
            (reading.position.Y * _PosScale / 32767.0) * 2.54,
            (reading.position.Z * _PosScale / 32767.0) * 2.54);

              Vector3 a = new Vector3(
            reading.angles.Azimuth * 180.0 / 32767.0,
            reading.angles.Elevation * 180.0 / 32767.0,
            reading.angles.Roll * 180.0 / 32767.0);

              Matrix3 o = new Matrix3();
              for (int i = 0 ; i < 3 ; i++)
            for (int j = 0 ; j < 3 ; j++)
              o[i, j] = reading.matrix[i, j] / 32767.0;

              AsyncOp.Post(OnPoseCallback, (new PoseEventArgs(frame.Time, p, a, o)));
              AsyncOp.Post(OnStatusCallback, new StatusEventArgs("Ok"));
            }
            else {
              System.Threading.Thread.Sleep(1); // Yield the rest of our time slice. Sleep(0) doesn't seem to work.
              // AsyncOp.Post(OnStatusCallback, new StatusEventArgs("No Data"));
            }
        }
コード例 #18
0
 private void ReportPercentage(AsyncOperation asyncOp)
 {
     if (((asyncOp != null) && (this.AccountListStatistics.AccountCount > 0L)) && (this.m_ProcessedNoticeCount > 0L))
     {
         asyncOp.Post(this.onProgressReportDelegate, new GenerationProgressChangedEventArgs(null, System.Convert.ToInt32((decimal) ((this.m_ProcessedNoticeCount / System.Convert.ToDecimal((long) (this.AccountListStatistics.AccountCount * this.Templates.get_Count()))) * 100M)), asyncOp.get_UserSuppliedState()));
     }
 }
コード例 #19
0
        // This method computes the list of prime numbers used by the
        // IsPrime method.
        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);

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

                    asyncOp.Post(this.onProgressReportDelegate, e);

                    primes.Add(n);

                    // Yield the rest of this time slice.
                    Thread.Sleep(0);
                }

                // Skip even numbers.
                n += 2;
            }

            return primes;
        }
コード例 #20
0
 private void PostProgressChanged(AsyncOperation asyncOp, PerformanceLog perfLog) {
     long percentageComplete = (m_progress.TotalTasksCompleted / m_progress.TotalTasksToComplete) * 100;
     asyncOp.Post(reportOperationProgressChanged, new OperationProgressChangedEventArgs((int)percentageComplete, perfLog, m_progress.TotalTasksCompleted, m_progress.TotalTasksToComplete));
 }
コード例 #21
0
 internal void PrepareToRaiseProgressChangedEvent(AsyncOperation asyncOP, ResolveProgressChangedEventArgs args)
 {
     asyncOP.Post(OnResolveProgressChangedDelegate, args);
 }
コード例 #22
0
 private void PostProgressChanged(AsyncOperation asyncOp, ProgressData progress) {
     if (asyncOp != null && progress.BytesSent + progress.BytesReceived > 0)
     {
         int progressPercentage;
         if (progress.HasUploadPhase)
         {
             if (progress.TotalBytesToReceive < 0 && progress.BytesReceived == 0)
             {
                 progressPercentage = progress.TotalBytesToSend < 0 ? 0 : progress.TotalBytesToSend == 0 ? 50 : (int)((50 * progress.BytesSent) / progress.TotalBytesToSend);
             }
             else
             {
                 progressPercentage = progress.TotalBytesToSend < 0 ? 50 : progress.TotalBytesToReceive == 0 ? 100 : (int) ((50 * progress.BytesReceived) / progress.TotalBytesToReceive + 50);
             }
             asyncOp.Post(reportUploadProgressChanged, new UploadProgressChangedEventArgs(progressPercentage, asyncOp.UserSuppliedState, progress.BytesSent, progress.TotalBytesToSend, progress.BytesReceived, progress.TotalBytesToReceive));
         }
         else
         {
             progressPercentage = progress.TotalBytesToReceive < 0 ? 0 : progress.TotalBytesToReceive == 0 ? 100 : (int) ((100 * progress.BytesReceived) / progress.TotalBytesToReceive);
             asyncOp.Post(reportDownloadProgressChanged, new DownloadProgressChangedEventArgs(progressPercentage, asyncOp.UserSuppliedState, progress.BytesReceived, progress.TotalBytesToReceive));
         }
     }
 }
コード例 #23
0
ファイル: DataCommit.cs プロジェクト: esrgc/etltool
 private void postProgress(string status, int progress, AsyncOperation asyncOp)
 {
     var progressArg = new OperationProgressChangedEventArgs(
         status,
         progress,
         asyncOp.UserSuppliedState);
     asyncOp.Post(onProgressReportCallback, progressArg);
 }
コード例 #24
0
ファイル: DumpLoader.cs プロジェクト: SayHalou/ospy
        private Dump DoLoad(Stream stream, AsyncOperation asyncOp)
        {
            Dump dump = new Dump();

            BinaryReader reader = new BinaryReader(stream, System.Text.Encoding.ASCII);

            string magic = new string(reader.ReadChars(4));
            uint version = reader.ReadUInt32();
            uint isCompressed = reader.ReadUInt32();
            uint numEvents = reader.ReadUInt32();

            if (magic != "oSpy")
                throw new InvalidDataException("invalid signature '" + magic + "'");
            else if (version != 2)
                throw new InvalidDataException("unsupported version " + version);
            else if (isCompressed != 0 && isCompressed != 1)
                throw new InvalidDataException("invalid value for isCompressed");

            if (isCompressed == 1)
                stream = new BZip2InputStream(stream);

            XmlTextReader xmlReader = new XmlTextReader(stream);

            uint eventCount;
            uint prevId = 0;

            for (eventCount = 0; xmlReader.Read() && eventCount < numEvents; )
            {
                if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "event")
                {
                    if (asyncOp != null)
                    {
                        int percentComplete = (int)(((float)(eventCount + 1) / (float)numEvents) * 100.0f);
                        ProgressChangedEventArgs e = new ProgressChangedEventArgs(percentComplete, asyncOp.UserSuppliedState);
                        asyncOp.Post(m_onProgressReportDelegate, e);
                    }

                    Event ev;

                    try
                    {
                        XmlReader rdr = xmlReader.ReadSubtree();
                        ev = m_eventFactory.CreateEvent(rdr);
                        m_tagBuilder.Process(ev);
                        dump.AddEvent(ev);
                    }
                    catch (Exception ex)
                    {
                        Exception outerEx = new Exception("Error processing event following id " + prevId, ex);
                        throw outerEx;
                    }

                    eventCount++;
                    prevId = ev.Id;
                }
            }

            if (eventCount != numEvents)
                throw new InvalidDataException(String.Format("expected {0} events, read {1}", numEvents, eventCount));

            return dump;
        }
コード例 #25
0
        // This method performs the actual file processing.
        // It is executed on the worker thread.
        private void processFileWorker(string filePath, IProcessingSettings settings,
            AsyncOperation asyncOp)
        {
            Exception e = null;

            // Check that the task is still active.
            // The operation may have been canceled before
            // the thread was scheduled.

            Task task = null;
            try
            {
                if (settings is ProcessingSettings)
                {
                    task = _syncClient.ProcessImage(filePath, settings as ProcessingSettings);
                }
                else if (settings is BusCardProcessingSettings)
                {
                    task = _syncClient.ProcessBusinessCard(filePath, settings as BusCardProcessingSettings);
                }
                else if (settings is CaptureDataSettings)
                {
                    string templateName = (settings as CaptureDataSettings).TemplateName;
                    task = _syncClient.CaptureData(filePath, templateName);
                }

                // Notify subscriber that upload completed
                Task uploadedTask = new Task(task.Id, TaskStatus.Submitted);
                UploadCompletedEventArgs uploadCompletedEventArgs = new UploadCompletedEventArgs(uploadedTask, asyncOp.UserSuppliedState);
                asyncOp.Post(onUploadCompletedDelegate, uploadCompletedEventArgs);

                startTaskMonitorIfNecessary();

                _taskList.AddTask(task);

                task = waitUntilTaskFinishes(task); // task is modified on server
            }
            catch (Exception ex)
            {
                e = ex;
            }

            processCompletionMethod(task, e, false, asyncOp);
        }
コード例 #26
0
ファイル: ProxyValidater.cs プロジェクト: Vinna/DeepInSummer
        private string ConnectValidatePage(AsyncOperation asyncOp, ProxyInfo info)
        {
            Natsuhime.Events.MessageEventArgs e = null;
            if (info != null)
            {
                try
                {
                    httper.Proxy = new System.Net.WebProxy(info.Address, info.Port);
                    System.Diagnostics.Debug.WriteLine(string.Format("{0}:{1}", info.Address, info.Port));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Write("error uri" + info.Address + "-" + info.Port);
                    e = new Natsuhime.Events.MessageEventArgs("", string.Format("[代理错误:{2}]{0}:{1}", info.Address, info.Port, ex.Message), "", asyncOp.UserSuppliedState);
                    asyncOp.Post(this.onStatusChangeDelegate, e);
                }
            }

            httper.Url = _ProxyValidateUrlInfo.Url;
            httper.Charset = _ProxyValidateUrlInfo.Charset;
            return httper.HttpGet();
        }
コード例 #27
0
ファイル: CollageGenerator.cs プロジェクト: piotrosz/Collage
 private void ReportProgress(AsyncOperation async, int colsCounter, int rowsCounter)
 {
     if (async != null)
     {
         int progressPercentage = this.progressCounter.GetProgressPercentage(colsCounter, rowsCounter);
         var args = new ProgressChangedEventArgs(progressPercentage, null);
         async.Post(e => this.OnCreateProgressChanged((ProgressChangedEventArgs)e), args);
     }
 }
コード例 #28
0
ファイル: PDManager.cs プロジェクト: Unathi/opensudoku
        private void doWaitForPD(AsyncOperation asyncOp)
        {
            m_isAlreadyWatingForPD = true;

            StateObject state = new StateObject();
            state.asyncOp = asyncOp;
            state.client = m_clientSocket;

            //Thread thread = new Thread(new ThreadStart(sendAll));
            //thread.Start();

            while (!Canceled)
            {
                try
                {

                    if (m_clientSocket.Client.Receive(state.buffer,  StateObject.BufferSize,  SocketFlags.None) >= PD.MIN_PACKET_SIZE)
                    {
                        PD currentReceivedPd = PDFactory.createPd(state.buffer);

                        if (currentReceivedPd != null)
                        {
                            asyncOp.Post(onProgressReportDelegate, new WaitForPDProgressChangedEventArgs(currentReceivedPd, 0, null));
                        }

            #if DEBUG
                        Console.WriteLine("==>Packet received : " + currentReceivedPd.ToString());
            #endif
                    }
                    else
                    {
                        ClientResetConnection();
                    }
                }
                catch(System.Net.Sockets.SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.ConnectionReset || e.SocketErrorCode == SocketError.Interrupted)
                    {
                        ClientResetConnection();
                        break;
                    }
                }
                catch (System.Exception e)
                {
            #if DEBUG
                    Console.WriteLine("Socket error " + e.Message);
            #endif

                    ClientResetConnection();
                    break;
                }

            }

            m_isAlreadyWatingForPD = false;
        }
コード例 #29
0
ファイル: AsyncTask.cs プロジェクト: daywrite/EApp
        protected virtual void ReportProgress(int progressPercentage, object userState, AsyncOperation asyncOperation)
        {
            Thread.Sleep(1000);

            ProgressChangedEventArgs e = new ProgressChangedEventArgs(progressPercentage, userState);

            asyncOperation.Post(this.onProgressChangedDelegate, e);
        }
コード例 #30
0
ファイル: Form1.cs プロジェクト: andrewirushkin/skype-sender
 // initialization
 private void initLaunch(AsyncOperation operation)
 {
     // в теле этого метода можно обращаться к любому контролу в UI.
     SendOrPostCallback callback = delegate(object state)
     {
         waiting.Text = (String)state;
     };
     try
     {
         if (!skype.Client.IsRunning)
         {
             skype.Client.Start(true, true);
             operation.Post(callback, "Запускаем скайп...");
             //Thread.Sleep(4000);
         }
         // Use skype protocol version 9
         skype.Attach(9, true);
         SKYPE4COMLib.UserCollection users = skype.Friends;
         int total = users.Count;
         int online = 0;
         foreach (SKYPE4COMLib.User user in users)
         {
             if (user.OnlineStatus != TOnlineStatus.olsOffline)
             {
                 online += 1;
             }
         }
         operation.Post(callback, "Контактов " + total + ", в сети - " + online);
     }
     catch
     {
         MessageBox.Show("Блиин, что-то пошло не так, попробуй перезапустить программу.", "Ошибка однако", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
 }
コード例 #31
0
ファイル: ProxyValidater.cs プロジェクト: Vinna/DeepInSummer
        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);
            }
        }
コード例 #32
0
ファイル: FileCopyClass.cs プロジェクト: jeanmahai/28helpmate
        private void FileCopyWorker(Manifest manifest, string sourcePath, AsyncOperation asyncOp)
        {
            Exception exception = null;
            FileCopyProgressChangedEventArgs e = null;
            Stream rStream = null;
            Stream wStream = null;
            double writeBytes = 0;
            string[] sourceFiles = null;
            string[] targetFiles = null;
            GetFiles(manifest, sourcePath, out sourceFiles, out targetFiles);
            if (!TaskCanceled(asyncOp.UserSuppliedState))
            {
                try
                {
                    double totalBytes = GetFileLength(sourceFiles);
                    byte[] buffer = new byte[writeFileLength];
                    int len = 0;
                    int offset = 0;
                    for (int i = 0; i < sourceFiles.Length; i++)
                    {
                        try
                        {
                            if (!Directory.Exists(Path.GetDirectoryName(targetFiles[i])))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(targetFiles[i]));
                            }
                            rStream = new FileStream(sourceFiles[i], FileMode.Open, FileAccess.Read, FileShare.None);
                            wStream = new FileStream(targetFiles[i], FileMode.Create, FileAccess.Write, FileShare.None);
                            while ((len = rStream.Read(buffer, offset, writeFileLength)) > 0)
                            {
                                wStream.Write(buffer, offset, len);
                                writeBytes += len;
                                e = new FileCopyProgressChangedEventArgs((int)(writeBytes / totalBytes * 100), asyncOp.UserSuppliedState);
                                e.SourceFileName = sourceFiles[i];
                                e.TargetFileName = targetFiles[i];
                                e.TotalBytesToCopy = totalBytes;
                                e.BytesToCopy = len;
                                e.Manifest = manifest;
                                asyncOp.Post(this.onProgressReportDelegate, e);
                                Thread.Sleep(1);
                            }
                        }
                        finally
                        {
                            DisposeStream(wStream);
                            DisposeStream(rStream);
                        }
                    }
                }
                catch (Exception ex)
                {
                    exception = ex;
                    OnFileCopyError(new FileCopyErrorEventArgs() { Error = ex, Manifest = manifest });
                }

                if (exception == null && targetFiles.Length > 0)
                {
                    //解压文件
                    string fileName = targetFiles.First();
                    ZipHelper.DeCompressionZip(fileName, Path.GetFullPath("."));
                    File.Delete(fileName);
                }
            }
            this.CompletionMethod(manifest, exception, TaskCanceled(asyncOp.UserSuppliedState), asyncOp);
        }
コード例 #33
0
ファイル: ProcessingPlugin.cs プロジェクト: EFanZh/EFanZh
 protected void DoProcessAsyncProgressChanged(AsyncOperation asyncOp, ProgressChangedEventArgs e)
 {
     asyncOp.Post(processAsyncProgressChangedDelegate, e);
 }
コード例 #34
0
 private void PostProgressChanged(AsyncOperation asyncOp, ProgressData progress)
 {
     if ((asyncOp != null) && ((progress.BytesSent + progress.BytesReceived) > 0L))
     {
         int num;
         if (progress.HasUploadPhase)
         {
             if ((progress.TotalBytesToReceive < 0L) && (progress.BytesReceived == 0L))
             {
                 num = (progress.TotalBytesToSend < 0L) ? 0 : ((progress.TotalBytesToSend == 0L) ? 50 : ((int) ((50L * progress.BytesSent) / progress.TotalBytesToSend)));
             }
             else
             {
                 num = (progress.TotalBytesToSend < 0L) ? 50 : ((progress.TotalBytesToReceive == 0L) ? 100 : ((int) (((50L * progress.BytesReceived) / progress.TotalBytesToReceive) + 50L)));
             }
             asyncOp.Post(this.reportUploadProgressChanged, new UploadProgressChangedEventArgs(num, asyncOp.UserSuppliedState, progress.BytesSent, progress.TotalBytesToSend, progress.BytesReceived, progress.TotalBytesToReceive));
         }
         else
         {
             num = (progress.TotalBytesToReceive < 0L) ? 0 : ((progress.TotalBytesToReceive == 0L) ? 100 : ((int) ((100L * progress.BytesReceived) / progress.TotalBytesToReceive)));
             asyncOp.Post(this.reportDownloadProgressChanged, new DownloadProgressChangedEventArgs(num, asyncOp.UserSuppliedState, progress.BytesReceived, progress.TotalBytesToReceive));
         }
     }
 }