/// <summary> /// Sub called by the worker to signal an exception /// </summary> /// <param name="workerException"> /// Exception /// </param> /// <remarks></remarks> internal void WorkerExceptionInternalSignal(Exception workerException) { if (_isAsynchonous && (_workerThread != null)) { _workerThread.Join(); _workerThread = null; } //Check if the results/exception have already been processed (because the owner was waiting for the worker to end) if (!_cancelWorkerDoneEvent) { //Prepare and raise the event for the owner to process var e = new WorkerDoneEventArgs <TResultType>(Identity, workerException, _worker.InterruptionRequested); if (WorkerDone != null) { WorkerDone(this, e); } } //If the worker was running in asynchronous mode, we also need to post the "complete" message if (_isAsynchonous) { _callingThreadAsyncOp.PostOperationCompleted(DoNothing, null); } }
/// <summary> /// 查询车次停靠站信息 /// </summary> /// <param name="train"></param> public void QueryInternal(QueryResultItem train) { var trainid = train.Id; var fromStatCode = train.FromStation.Code; var toStatCode = train.ToStation.Code; var depDate = train.FromStation.DepartureTime.Value; var firstStationTime = train.StartStation.DepartureTime; var data = new { train_no = trainid, from_station_telecode = fromStatCode, to_station_telecode = toStatCode, depart_date = depDate.ToString("yyyy-MM-dd") }; var task = Session.NetClient.Create <TrainStopResponse>(HttpMethod.Get, "czxx/queryByTrainNo", "leftTicket/init", data).Send(); if (task == null || !task.IsSuccess || task.Result?.Data?.Data == null) { Error = task?.Exception; Success = false; if (_operation == null) { OnLoadFailed(); } else { _operation.PostOperationCompleted(_ => OnLoadFailed(), null); } } else { Result = task.Result.Data.Data; Result.ApplyTime(train, firstStationTime, depDate); Success = true; if (_operation == null) { OnLoadComplete(); } else { _operation.PostOperationCompleted(_ => OnLoadComplete(), null); } } }
/// <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); }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="result"></param> /// <param name="x"></param> /// <param name="cancelled"></param> /// <param name="asyncOp"></param> /// <remarks> /// This is the method that the underlying, free-threaded /// asynchronous behavior will invoke. This will happen on /// an arbitrary thread. /// </remarks> protected void GetProfileCompletionMethod(string entity, string profile, Exception x, bool cancelled, AsyncOperation asyncOp) { // If the task was not previously cancelled, // remove the task from the lifetime collection. if (!cancelled) { lock (userStateToLifetime.SyncRoot) { userStateToLifetime.Remove(asyncOp.UserSuppliedState); } } // Package the results of the operation in a // ProfileRetrievedEventArgs. GetProfileCompletedEventArgs e = new GetProfileCompletedEventArgs( entity, profile, x, cancelled, asyncOp.UserSuppliedState); // End the task. The asyncOp object is responsible // for marshaling the call. asyncOp.PostOperationCompleted(onGetProfileCompletedDelegate, e); // Note that after the call to OperationCompleted, // asyncOp is no longer usable, and any attempt to use it // will cause an exception to be thrown. }
// This is the method that the underlying, free-threaded // asynchronous behavior will invoke. This will happen on // an arbitrary thread. private void CompletionMethod( List <ProxyInfo> proxylistOk, Exception exception, bool canceled, AsyncOperation asyncOp) { // If the task was not previously canceled, // remove the task from the lifetime collection. if (!canceled) { lock (userStateToLifetime.SyncRoot) { userStateToLifetime.Remove(asyncOp.UserSuppliedState); } } // Package the results of the operation in a // CalculatePrimeCompletedEventArgs. CompletedEventArgs e = new CompletedEventArgs( proxylistOk, exception, canceled, asyncOp.UserSuppliedState); // End the task. The asyncOp object is responsible // for marshaling the call. asyncOp.PostOperationCompleted(onCompletedDelegate, e); // Note that after the call to OperationCompleted, // asyncOp is no longer usable, and any attempt to use it // will cause an exception to be thrown. }
/// <summary> /// Completion /// </summary> /// <param name="exception"></param> /// <param name="canceled"></param> /// <param name="asyncOp"></param> /// <param name="args"></param> protected void Completion(Exception exception, Boolean canceled, AsyncOperation asyncOp, params object[] args) { // If the task was not previously canceled, // remove the task from the lifetime collection. if (!canceled) { lock (_taskIdToLifetime.SyncRoot) { _taskIdToLifetime.Remove(asyncOp.UserSuppliedState); } } // Package the results of the operation in a // DeviceConnectionCompletedEventArgs. List <Object> instanceArgs = new List <Object>(); instanceArgs.Add(exception); instanceArgs.Add(canceled); instanceArgs.Add(asyncOp.UserSuppliedState); if (args != null) { foreach (var arg in args) { instanceArgs.Add(arg); } } Object e = Activator.CreateInstance(typeof(TCompletedEventArgs), instanceArgs.ToArray()); // End the task. The asyncOp object is responsible // for marshaling the call. asyncOp.PostOperationCompleted(_onCompletedDelegate, e); // Note that after the call to OperationCompleted, // asyncOp is no longer usable, and any attempt to use it // will cause an exception to be thrown. }
// This is the method that the underlying, free-threaded // asynchronous behavior will invoke. This will happen on // an arbitrary thread. private void OnAsyncCompletionMethod(object operationState) { AsyncData data = operationState as AsyncData; AsyncOperation asyncOp = data.Operation; AsyncOperationCompletedEventArgs args = new AsyncOperationCompletedEventArgs(data); // In this case, don't allow cancellation, as the method // is about to raise the completed event. lock (this.userStateToLifetime.SyncRoot) { if (!userStateToLifetime.Contains(data.UserData)) { asyncOp = null; } else { this.userStateToLifetime.Remove(asyncOp.UserSuppliedState); } } // The asyncOp object is responsible for marshaling // the call. if (asyncOp != null) { asyncOp.PostOperationCompleted(this.onCompletedDelegate, args); } // Note that after the call to OperationCompleted, // asyncOp is no longer usable, and any attempt to use it // will cause an exception to be thrown. }
private void DownLoadCallBack(IAsyncResult ar) { var del = ar.AsyncState as Func <string, string, AsyncOperation, string>; var res = del.EndInvoke(ar); asyncOpe.PostOperationCompleted(onDownloadCompletedDelegate, new AsyncCompletedEventArgs(null, false, res)); }
/// <summary> /// Ends the lifetime of an asynchronous operation. /// </summary> /// <param name="asyncOp"></param> /// <param name="runner">A <see cref="Action"/> that wraps the delegate to be called when the operation ends.</param> public static void PostOperationCompleted(this AsyncOperation asyncOp, [InstantHandle] Action runner) { Code.NotNull(asyncOp, nameof(asyncOp)); Code.NotNull(runner, nameof(runner)); asyncOp.PostOperationCompleted(_ => runner(), null); }
private void CalculateWorker(int numberToTest, AsyncOperation asyncOp) { bool isPrime = false; int firstDivisor = 1; Exception e = null; if (!TaskCanceled(asyncOp.UserSuppliedState)) { try { ArrayList primes = BuildPrimeNumberList(numberToTest, asyncOp); isPrime = IsPrime(primes, numberToTest, out firstDivisor); } catch (Exception ex) { e = ex; } } if (!TaskCanceled(asyncOp.UserSuppliedState)) { lock (userStateToLifetime.SyncRoot) { userStateToLifetime.Remove(asyncOp.UserSuppliedState); } } CalculatePrimeCompletedEventArgs eventArgs = new CalculatePrimeCompletedEventArgs(e, TaskCanceled(asyncOp.UserSuppliedState), asyncOp.UserSuppliedState); asyncOp.PostOperationCompleted(onCompletedDelegate, eventArgs); }
private void ContinueAsyncSend(object state) { // // FxCop: need to snapshot the address here, so we're sure that it's not changed between the permission // and the operation, and to be sure that IPAddress.ToString() is called and not some override that // always returns "localhost" or something. // Debug.Assert(asyncOp != null, "Null AsyncOp?"); AsyncStateObject stateObject = (AsyncStateObject)state; try { IPAddress addressSnapshot = Dns.GetHostAddresses(stateObject.hostName)[0]; (new NetworkInformationPermission(NetworkInformationAccess.Ping)).Demand(); InternalSend(addressSnapshot, stateObject.buffer, stateObject.timeout, stateObject.options, true); } catch (Exception e) { PingException pe = new PingException(SR.GetString(SR.net_ping), e); PingCompletedEventArgs eventArgs = new PingCompletedEventArgs(null, pe, false, asyncOp.UserSuppliedState); Finish(true); asyncOp.PostOperationCompleted(onPingCompletedDelegate, eventArgs); } }
private void LoadingWork(RawTile tileKey, AsyncOperation asyncOp) { MemoryStream ms = null; Exception ex = null; object taskID = tileKey as object; bool canceled = true; if (!TaskCanceled(taskID)) { try { ms = loadProxy.GetTile(tileKey); } catch (Exception exception) { ex = exception; } canceled = TaskCanceled(taskID); lock (userStateToLifetime.SyncRoot) userStateToLifetime.Remove(asyncOp.UserSuppliedState); } TileLoadCompletedEventArgs e = new TileLoadCompletedEventArgs(tileKey, ms, ex, canceled, taskID); if (--loadingTaskNum == 0) { //OnMapLoadCompleted(new MapLoadCompletedEventArgs()); IsLoading = false; } asyncOp.PostOperationCompleted(new SendOrPostCallback(OnTileLoadCompleted), e); }
private void CompletionMethod( byte[] responseData, Exception exception, bool canceled, AsyncOperation asyncOp) { // If the task was not previously canceled, // remove the task from the lifetime collection. if (!canceled) { lock (userStateToLifetime.SyncRoot) { userStateToLifetime.Remove(asyncOp.UserSuppliedState); } } RequestDataCompletedEventArgs e = new RequestDataCompletedEventArgs( responseData, exception, canceled, asyncOp.UserSuppliedState); // End the task. The asyncOp object is responsible // for marshaling the call. asyncOp.PostOperationCompleted(onRequestDataCompletedDelegate, e); // Note that after the call to OperationCompleted, // asyncOp is no longer usable, and any attempt to use it // will cause an exception to be thrown. }
/// <summary> /// Executes the specified service method completion sink. /// </summary> /// <param name = "serviceMethodUiBridge">The service method completion sink.</param> public void Execute(IServiceMethodUiBridge serviceMethodUiBridge) { m_ServiceMethodUiBridge = serviceMethodUiBridge; AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(m_AsyncKey); try { Feature feature = BuildFeature(serviceMethodUiBridge); CreateFeatureRequest request = CreateFeatureRequest.Create(MessageIdFactory.GenerateMessageId(), feature); IFeatureStoreServiceProxy featureStoreServiceProxy = new FeatureStoreServiceProxy(); featureStoreServiceProxy.BeginCreateFeature( request, ar => { string rtfResults; try { CreateFeatureResponse response = featureStoreServiceProxy.EndCreateFeature(ar); rtfResults = BuildResultsRichText(request, response, GetType().Name); } catch (Exception e) { rtfResults = BuildExceptionRichText(e); } asyncOperation.PostOperationCompleted(HandleEndAsync, rtfResults); }, null); } catch (Exception e) { serviceMethodUiBridge.DisplayResults(BuildExceptionRichText(e)); } }
private void WorkerThreadStart(TInput input) { var result = default(TOutput); Exception error = null; var cancelled = false; try { var eventArgs = new DoWorkEventArgs <TInput, TOutput>(input); OnDoWork(eventArgs); if (eventArgs.Cancel) { cancelled = true; } else { result = eventArgs.Result; } } catch (Exception exception) { error = exception; } var arg = new RunWorkerCompletedEventArgs <TOutput>(result, error, cancelled); AsyncOperation.PostOperationCompleted(operationCompleted, arg); }
public static void CancelAsync(AsyncGuessState guessState) { if (guessState == null) { throw new ArgumentNullException("guessState"); } AsyncOperation asyncOp = guessState.AsyncOperation; GuessCompletedEventArgs e = new GuessCompletedEventArgs( guessState, null, true, guessState); try { asyncOp.PostOperationCompleted(GuessCompleted, e); } catch (InvalidOperationException) { } guessState.Canceled = true; }
private void CalculateWorker(decimal number, AsyncOperation asyncOp) { bool isPrime = false; double seconds = 0.0; Exception exception = null; if (!TaskCanceled(asyncOp.UserSuppliedState)) { try { isPrime = IsPrimeInternal(number, out seconds, asyncOp); } catch (Exception ex) { exception = ex; } } if (TaskCanceled(asyncOp.UserSuppliedState)) { _userStateToLifetime.TryRemove(asyncOp.UserSuppliedState, out AsyncOperation value); } var args = new PrimeNumberCheckCompletedEventArgs(number, isPrime, seconds, exception, TaskCanceled(asyncOp.UserSuppliedState), asyncOp.UserSuppliedState); asyncOp.PostOperationCompleted(_completedDelegate, args); }
private void CompletionMethod(List <T> items, Exception exception, bool canceled, AsyncOperation asyncOp) { //package the results of the operation in an XMLRPCCompletedEventArgs object XMLRPCCompletedEventArgs <T> args = new XMLRPCCompletedEventArgs <T>(items, exception, canceled, asyncOp.UserSuppliedState); asyncOp.PostOperationCompleted(onCompletedDelegate, args); }
public void StopImmediately() { if (!IsBusy || mThread == null) { return; } try { CancelAsync(); mThread.Suspend(); Thread.SpinWait(10); mThread.Abort(); } catch (ThreadAbortException) { //swallow thread abort in this part, even though it will propogate onwards } catch (Exception ex) { } try { //OnRunWorkerCompleted(new RunWorkerCompletedEventArgs(null, null, true)); threadAborted = true; //setPrivateFieldValue<bool>("isRunning", false); AsyncOperation op = getPrivateFieldValue <AsyncOperation>("asyncOperation"); SendOrPostCallback completionCallback = getPrivateFieldValue <SendOrPostCallback>("operationCompleted"); RunWorkerCompletedEventArgs completedArgs = new RunWorkerCompletedEventArgs(null, null, true); op.PostOperationCompleted(completionCallback, completedArgs); } catch (Exception ex) { } }
public static void CancelAsync(AsyncTranslateState translateState) { if (translateState == null) { throw new ArgumentNullException("translateState"); } AsyncOperation asyncOp = translateState.AsyncOperation; translateState.RemoveTimers(); TranslateCompletedEventArgs e = new TranslateCompletedEventArgs( translateState, null, true, translateState); // The asyncOp object is responsible for marshaling // the call. try { //some time operation already completed asyncOp.PostOperationCompleted(TranslateCompleted, e); } catch (InvalidOperationException) { } translateState.IsTerminated = true; }
private void WorkerThreadStart(object argument) { object workerResult = null; Exception error = null; bool cancelled = false; try { DoWorkEventArgs doWorkArgs = new DoWorkEventArgs(argument); OnDoWork(doWorkArgs); if (doWorkArgs.Cancel) { cancelled = true; } else { workerResult = doWorkArgs.Result; } } catch (Exception exception) { error = exception; } RunWorkerCompletedEventArgs e = new RunWorkerCompletedEventArgs(workerResult, error, cancelled); asyncOperation.PostOperationCompleted(operationCompleted, e); }
void GetInternal() { var client = new WebLib.NetClient(); var task = client.Create <XmlDocument>(HttpMethod.Get, "https://blog.iccfish.com/feed/", "").Send(); if (task == null || !task.IsSuccess || task.Result == null) { Success = false; } else { Success = true; SystemNotice = new List <SystemNotice>(); var nodes = task.Result.SelectNodes("//item"); foreach (var node in nodes.Cast <XmlNode>()) { var no = new SystemNotice(node.SelectSingleNode("title").InnerText.Trim(), node.SelectSingleNode("link").InnerText.Trim(), node.SelectSingleNode("pubDate").InnerText.Trim().ToDateTimeNullable() ?? DateTime.Now, false, node.SelectSingleNode("description").InnerText.Trim() ); SystemNotice.Add(no); } } _operation.PostOperationCompleted(_ => OnDownloadComplete(), null); }
//private void DownloadBlobWorker(MyAsyncContext asyncContext, out bool cancelled, AsyncOperation async) //{ // cancelled = false; // ParallelDownloadFile(asyncContext, async); // // check for Cancelling // if (asyncContext.IsCancelling) // { // cancelled = true; // } //} private void TaskCompletedCallback(IAsyncResult ar) { // get the original worker delegate and the AsyncOperation instance BlobTransferWorkerDelegate worker = (BlobTransferWorkerDelegate)((AsyncResult)ar).AsyncDelegate; AsyncOperation async = (AsyncOperation)ar.AsyncState; bool cancelled; // finish the asynchronous operation worker.EndInvoke(out cancelled, ar); // clear the running task flag lock (_sync) { TaskIsRunning = false; TaskContext = null; } // raise the completed event var asyncOperation = ar.AsyncState as AsyncOperation; object userState = null; if (asyncOperation != null) { userState = asyncOperation.UserSuppliedState; } AsyncCompletedEventArgs completedArgs = new AsyncCompletedEventArgs(null, cancelled, userState); async.PostOperationCompleted(delegate(object e) { OnTaskCompleted((AsyncCompletedEventArgs)e); }, completedArgs); }
private void InternalDownloadHtmlAsync(Uri address, AsyncOperation asyncOperation) { string html = InternalDownloadHtml(address); DownloadHtmlCompletedEventArgs e = new DownloadHtmlCompletedEventArgs(null, false, html); asyncOperation.PostOperationCompleted(DownloadHtmlCompletedCallBack, e); }
public void QueueMessageMark( [NotNull] IEnumerable <ForumEntryIds> msgIds, bool isRead, Action markFinished) { if (msgIds == null) { throw new ArgumentNullException("msgIds"); } var msgIdsArray = msgIds.ToArray(); using (_rwLock.GetWriterLock()) { AsyncOperation asyncOp = null; if (markFinished != null) { asyncOp = AsyncHelper.CreateOperation(); } _requests.Add( new MarkRequest( msgIdsArray, isRead, () => { if (markFinished != null) { // ReSharper disable AssignNullToNotNullAttribute asyncOp.PostOperationCompleted(markFinished); } // ReSharper restore AssignNullToNotNullAttribute })); _syncEvent.Set(); EnsureThread(); } }
//Does the actual work private static void EvenNumbersWorker(int min, int max, AsyncOperation asyncOp) { for (int i = min; i <= max; i++) { Thread.Sleep(3000); if (i % 2 == 0) { Console.Write($"{i} is even!\n"); } } Console.WriteLine("Done with the evens!"); //SyncRoot gets an object that can be used to //synchronize acces to the HybridDictionary lock (tasks.SyncRoot) { //UserSuppliedState gets or sets an object used to uniquely //identify an async operation tasks.Remove(asyncOp.UserSuppliedState); } GetEvenNumberEventArgs arg = new GetEvenNumberEventArgs(null, false, asyncOp.UserSuppliedState); asyncOp.PostOperationCompleted(onCompletedDelegate_Even, arg); }
private void WorkerThreadStart() { TResult workerResult = default(TResult); Exception error = null; bool cancelled = false; try { DoWorkEventArgs <TArgument, TResult> doWorkArgs = new DoWorkEventArgs <TArgument, TResult>((TArgument)asyncOperation.UserSuppliedState); OnDoWork(doWorkArgs); if (doWorkArgs.Cancel) { cancelled = true; } else { workerResult = doWorkArgs.Result; } } catch (Exception exception) { error = exception; } RunWorkerCompletedEventArgs <TResult> e = new RunWorkerCompletedEventArgs <TResult>(workerResult, error, cancelled); asyncOperation.PostOperationCompleted(operationCompleted, e); }
// This is the method that the underlying, free-threaded // asynchronous behavior will invoke. This will happen on // a worker thread private void processCompletionMethod( Task task, Exception exception, bool canceled, AsyncOperation asyncOp) { // If the task was not previously canceled, // remove the task from the lifetime collection. if (!canceled) { lock (processJobs.SyncRoot) { processJobs.Remove(asyncOp.UserSuppliedState); } } // Package the results of the operation in EventArgs TaskEventArgs e = new TaskEventArgs(task, exception, canceled, asyncOp.UserSuppliedState); // End the task. The asyncOp object is responsible // for marshaling the call. asyncOp.PostOperationCompleted(onProcessingCompleteDelegate, e); // Note that after the call to OperationCompleted, // asyncOp is no longer usable, and any attempt to use it // will cause an exception to be thrown. }
private void UpdateJobStatusCompletionMethod( string status, Exception exception, bool canceled, AsyncOperation asyncOp) { // If the task was not previously canceled, // remove the task from the lifetime collection. if (!canceled) { lock (userStateToLifetimeUpdateStatus.SyncRoot) { userStateToLifetimeUpdateStatus.Remove(asyncOp.UserSuppliedState); } } // Output SendFileCompletedEventArgs UpdateStatusCompleteEventArgs e = new UpdateStatusCompleteEventArgs(status, exception, canceled, asyncOp.UserSuppliedState); // End the task. The asyncOp object is responsible // for marshaling the call. asyncOp.PostOperationCompleted(onUpdateJobStatusCompleted, e); }
// wrapper used by async method to call sync version of method, matches WaitCallback so it // can be queued by the thread pool private void DoSomethingAsyncCore(object state) { int returnValue = DoSomething(); var e = new DoSomethingCompletedEventArgs(returnValue); _operation.PostOperationCompleted(RaiseDoSomethingCompleted, e); }