当前位置: 首页>>代码示例>>C#>>正文


C# AsyncOperation.Post方法代码示例

本文整理汇总了C#中System.ComponentModel.AsyncOperation.Post方法的典型用法代码示例。如果您正苦于以下问题:C# AsyncOperation.Post方法的具体用法?C# AsyncOperation.Post怎么用?C# AsyncOperation.Post使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.ComponentModel.AsyncOperation的用法示例。


在下文中一共展示了AsyncOperation.Post方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: IndexerThread

        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); ;
        }
开发者ID:Ejik,项目名称:chkaddr,代码行数:13,代码来源:MockMdbService.cs

示例2: doWaitForPD

        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;
        }
开发者ID:Unathi,项目名称:opensudoku,代码行数:56,代码来源:PDManager.cs

示例3: Validate

        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);
            }
        }
开发者ID:Vinna,项目名称:DeepInSummer,代码行数:53,代码来源:ProxyValidater.cs

示例4: ReportProgress

        protected virtual void ReportProgress(int progressPercentage, object userState, AsyncOperation asyncOperation)
        {
            Thread.Sleep(1000);

            ProgressChangedEventArgs e = new ProgressChangedEventArgs(progressPercentage, userState);

            asyncOperation.Post(this.onProgressChangedDelegate, e);
        }
开发者ID:daywrite,项目名称:EApp,代码行数:8,代码来源:AsyncTask.cs

示例5: ReportProgress

 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);
     }
 }
开发者ID:piotrosz,项目名称:Collage,代码行数:9,代码来源:CollageGenerator.cs

示例6: processFileWorker

        // 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);
        }
开发者ID:Jeff-Tian,项目名称:ocrsdk.com,代码行数:46,代码来源:RestServiceClientAsync.cs

示例7: SensorLiveScanProcedure

 /// <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) { }
         }
     }
 }
开发者ID:vc,项目名称:from-editor,代码行数:27,代码来源:SensorMonitoringParams.cs

示例8: PostProgressChanged

 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));
 }
开发者ID:XewTurquish,项目名称:vsminecraft,代码行数:4,代码来源:AsyncOperation.cs

示例9: run

        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"));
            }
        }
开发者ID:rpavlik,项目名称:chromium,代码行数:39,代码来源:FlockOfBirds.cs

示例10: ReportPercentage

 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()));
     }
 }
开发者ID:u4097,项目名称:SQLScript,代码行数:7,代码来源:NoticeReportGenerator.cs

示例11: BuildPrimeNumberList

        // 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;
        }
开发者ID:akhuang,项目名称:NetExercise,代码行数:41,代码来源:PrimeNumberCalculator.cs

示例12: ParallelUploadFile

        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();
//.........这里部分代码省略.........
开发者ID:ntotten,项目名称:bob-share,代码行数:101,代码来源:BlobTransfer.cs

示例13: FileCopyWorker

        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);
        }
开发者ID:jeanmahai,项目名称:28helpmate,代码行数:65,代码来源:FileCopyClass.cs

示例14: DoSave

        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();
        }
开发者ID:SayHalou,项目名称:ospy,代码行数:42,代码来源:DumpSaver.cs

示例15: PostProgressChanged

 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));
         }
     }
 }
开发者ID:gbarnett,项目名称:shared-source-cli-2.0,代码行数:23,代码来源:webclient.cs


注:本文中的System.ComponentModel.AsyncOperation.Post方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。