public void Dispose() { _callback = null; _state = null; _changeSource?.Cancel(); _changeSource?.Dispose(); }
public Task<GetManyResult> GetManyAsync( Guid clientGuid, string domain, FactTreeMemento tree, Dictionary<long, long> pivotIds, int timeoutSeconds) { GetManyResult result = GetManyInternal(clientGuid, domain, tree, pivotIds); if (timeoutSeconds > 0 && !result.Tree.Facts.Any()) { CancellationTokenSource cancellation = new CancellationTokenSource(); int session = _messageBus.Register( domain, result.LocalPivotIds, clientGuid, () => cancellation.Cancel()); return Task .Delay(timeoutSeconds * 1000, cancellation.Token) .ContinueWith(t => t.IsCanceled ? GetManyInternal(clientGuid, domain, tree, pivotIds) : result) .ContinueWith(t => { _messageBus.Unregister(session); cancellation.Dispose(); return t.Result; }); } return Task.FromResult(result); }
static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); cts.CancelAfter(1000); Stopwatch watch = new Stopwatch(); watch.Start(); InternalGetIntAsync(cts.Token).ContinueWith((task) => { Console.WriteLine("Elapsed time: {0}ms", watch.Elapsed.TotalMilliseconds); watch.Stop(); //We get the response. //Dispose of the CancellationTokenSource //so that it is not going to signal. cts.Dispose(); if (task.Status == TaskStatus.RanToCompletion) { Console.WriteLine(task.Result); } else if (task.Status == TaskStatus.Canceled) { Console.WriteLine("The task has been canceled."); } else { Console.WriteLine("An error has been occurred. Details:"); Console.WriteLine(task.Exception.InnerException.Message); } }); Console.ReadLine(); }
private void button2_Click(object sender, EventArgs e) { Service service = new Service(); int expectedDuration = 10; ToOutput("[Started] Worker with progress ({0} seconds)", expectedDuration); m_cts = new CancellationTokenSource(); button2.Enabled = false; Task.Factory.StartNew(() => service.DoWithProgress(expectedDuration, progress => { Invoke((Action) delegate { ToOutput("[Progress] Worker with progress ({0})", progress); }); }, m_cts.Token), m_cts.Token) .ContinueWith(data => { if (m_cts.IsCancellationRequested) ToOutput("[Cancelled] Worker with progress"); ToOutput("[Completed] Worker with progress"); m_cts.Dispose(); m_cts = null; button2.Enabled = true; }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext()); }
void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance) { var cancel = new System.Threading.CancellationTokenSource(); taskInstance.Canceled += (s, e) => { cancel.Cancel(); cancel.Dispose(); }; BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try { // Handle geofence state change reports GetGeofenceStateChangedReports(GeofenceMonitor.Current.LastKnownGeoposition); } catch (UnauthorizedAccessException) { WriteStatusToAppData("Location permissions are disabled. Enable access through the settings."); } finally { deferral.Complete(); } }
public async static Task<string> DownloadStringAsync(string url) { var tcs = new CancellationTokenSource(); var client = new HttpClient(); lock (lck) { cancelTokens.Add(tcs); } string res = null; try { var x = await client.GetAsync(url, tcs.Token); res = await x.Content.ReadAsStringAsync(); } catch (Exception e) { } finally { client.Dispose(); lock (lck) { cancelTokens.Remove(tcs); } tcs.Dispose(); } return res; }
static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); // Create an opportunity for the user to cancel. Task.Run(() => { if (Console.ReadKey().KeyChar == 'c' || Console.ReadKey().KeyChar == 'C') cts.Cancel(); }); ObjectPool<TestClass> pool = new ObjectPool<TestClass>(() => new TestClass()); // Create a high demand for MyClass objects. Parallel.For(0, 1000000, (i, loopState) => { using(TestClass mc = pool.GetResource()) { Console.CursorLeft = 0; // This is the bottleneck in our application. All threads in this loop // must serialize their access to the static Console class. Console.WriteLine("{0:####.####}", mc.GetValue(i)); // pool.PoolResource(mc); alternative to implementing repool in the dispose method } if (cts.Token.IsCancellationRequested) loopState.Stop(); }); Console.WriteLine("Press the Enter key to exit."); Console.ReadLine(); cts.Dispose(); }
private void DoSomeLongRunningTask(int operationId, CancellationTokenSource cts) { // Kick off the long running operation in the background Task.Run(async () => { // When the cts trips we're going to call the client back and tell them the operation is cancelled CancellationTokenRegistration registration = cts.Token.Register(() => Clients.Caller.cancelled(operationId)); // Pretend to something long running await Task.Delay(5000); // Don't call complete if we're cancelled if (!cts.IsCancellationRequested) { Clients.Caller.complete(operationId); } // Don't leak registrations registration.Dispose(); // Remove it from the list of pending operations _pendingOperations.TryRemove(operationId, out cts); // Might not need this but lets not forget to dispose anything cts.Dispose(); }); }
public void Display(bool isOn) { canvasGroup.alpha = (isOn) ? 1 : 0; if (isOn) { cancelToken = new System.Threading.CancellationTokenSource(); logo_holo_animator.SetTrigger(EventFlag.Animation.Reset); EventImageWallShowComplete += OnImageWallShowComplete; GenerateImageWall(); } else { logo_holo_animator.SetTrigger(EventFlag.Animation.Reset); Debug.Log("Reset"); if (cancelToken != null) { cancelToken.Cancel(); cancelToken.Dispose(); cancelToken = null; } fileUtility.RefreshImageRecordDisplay(); EventImageWallShowComplete -= OnImageWallShowComplete; } }
static void Main() { Console.WriteLine("Основной поток запущен"); // Объект источника признаков отмены CancellationTokenSource cancelTokSSrc = new CancellationTokenSource(); // Запустить задачу, передав ей признак отмены Task tsk = Task.Factory.StartNew(MyTask, cancelTokSSrc.Token, cancelTokSSrc.Token); Thread.Sleep(2000); try { // отменить задачу cancelTokSSrc.Cancel(); tsk.Wait(); } catch (AggregateException exc) { if (tsk.IsCanceled) Console.WriteLine("Задача tsk отменена"); } finally { tsk.Dispose(); cancelTokSSrc.Dispose(); } Console.WriteLine("Основной поток завершен"); Console.ReadLine(); }
private async void getImagesButton_Click(object sender, EventArgs e) { // start the timer for updating the UI progressTimer.Enabled = true; cancelButton.Enabled = true; getImagesButton.Enabled = false; // Get and process all images, but don't block the UI thread try { // Create to get a cancellation token for the job source = new CancellationTokenSource(); // Create a job counters object, to be updated by the async task counters = new MongoUniversityPlugin.JobCounters(); int count = await (this.Plugin as MongoUniversityPlugin).GetImages(source.Token, counters); // this will wait for completion of the above (it's async though!) countTextBox.Text = count.ToString(); } catch (OperationCanceledException ex) { MessageBox.Show("The operation was cancelled"); source.Dispose(); } finally { // stop the timer progressTimer.Enabled = false; cancelButton.Enabled = false; getImagesButton.Enabled = true; UpdateCounters(); } }
// This method evaluates the expression asynchronously. // This method should return immediately after it has started the expression evaluation. // When the expression is successfully evaluated, an IDebugExpressionEvaluationCompleteEvent2 // must be sent to the IDebugEventCallback2 event callback int IDebugExpression2.EvaluateAsync(enum_EVALFLAGS dwFlags, IDebugEventCallback2 pExprCallback) { _tokenSource = new CancellationTokenSource(); _frame.StackFrame.ExecuteTextAsync(_expression, _tokenSource.Token) .ContinueWith(p => { try { IDebugProperty2 property; if (p.Exception != null && p.Exception.InnerException != null) { property = new AD7EvalErrorProperty(p.Exception.InnerException.Message); } else if (p.IsCanceled) { property = new AD7EvalErrorProperty("Evaluation canceled"); } else if (p.IsFaulted || p.Result == null) { property = new AD7EvalErrorProperty("Error"); } else { property = new AD7Property(_frame, p.Result); } _tokenSource.Token.ThrowIfCancellationRequested(); _frame.Engine.Send( new AD7ExpressionEvaluationCompleteEvent(this, property), AD7ExpressionEvaluationCompleteEvent.IID, _frame.Engine, _frame.Thread); } finally { _tokenSource.Dispose(); _tokenSource = null; } }, _tokenSource.Token); return VSConstants.S_OK; }
private static void cleanUp(List<Task> tasks, CancellationTokenSource cancelToken) { // cancel tasks cancelToken.Cancel(); try { // wait until all tasks are finished Task.WaitAll(tasks.ToArray()); } catch (AggregateException e) { foreach (var inner in e.InnerExceptions) { if (inner is TaskCanceledException) continue; else Console.WriteLine("Exception while stopping: {0} {1}", inner.GetType().Name, inner.Message); } } finally { tasks = null; cancelToken.Dispose(); } }
public CancellationTokenSource CreateTask( long agentId ) { CancellationTokenSource source = new CancellationTokenSource(); var task = new Task( async () => { while( !source.Token.IsCancellationRequested ) { try { using( AgentServiceClient client = new AgentServiceClient() ) { await client.HandshakeAsync( agentId ); while( !source.Token.IsCancellationRequested ) { Thread.Sleep( 1000 ); await client.DoOperationAsync(); } } } catch { Thread.Sleep( 1000 ); } } source.Dispose(); }, source.Token ); task.Start(); return source; }
public async void AsyncError() { CancellationTokenSource source = new CancellationTokenSource(); var token = source.Token; int i = 0; var t = Task.Factory.StartNew(() => { token.Register(() => { Debug.WriteLine("End"); }, true); while (i++ < 20 && !token.IsCancellationRequested) { Debug.WriteLine(i.ToString()); Thread.Sleep(100); } }, token, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); var t1 = Task.Factory.StartNew(() => { Thread.Sleep(500); source.Cancel(); }); try { Task.WaitAll(t, t1); } finally { source.Dispose(); } }
static void Main(string[] args) { var verbose = args.Length > 0 && args[0] == "-v"; var cts = new CancellationTokenSource (); // trapping Ctrl+C as exit signal! Console.CancelKeyPress += (s, e) => { e.Cancel = true; cts.Cancel (); }; Console.WriteLine ("Starting Titanic Broker in {0} - mode.\n\n", verbose ? "verbose" : "silent"); using (var titanic = new TitanicBroker (new TitanicMemoryIO ())) { if (verbose) titanic.LogInfoReady += (s, e) => PrintMessage (e.Info); try { Task.Factory.StartNew (() => titanic.Run (), cts.Token).Wait (cts.Token); } catch (AggregateException e) { Console.WriteLine (e.Flatten ()); } finally { cts.Dispose (); } } }
public static void CanCancel(Action<CancellationToken> work, string message = null) { CancellationTokenSource cts = new CancellationTokenSource(); ConsoleCancelEventHandler cancelKeyPress = (sender, e) => { e.Cancel = true; cts.Cancel(); Console.WriteLine("command interrupting..."); }; Console.CancelKeyPress += cancelKeyPress; try { work(cts.Token); } finally { Console.CancelKeyPress -= cancelKeyPress; } if (cts.Token.IsCancellationRequested) { if (message == null) message = "command interrupted"; Console.WriteLine(); Console.WriteLine(message); } cts.Dispose(); }
public static int Main(string[] args) { Logger.Info("Application started."); AppDomain.CurrentDomain.UnhandledException += OnUnhandledApplicationException; Executer = new CodeExecuter(); TokenSource = new CancellationTokenSource(); try { var task = Task.Factory.StartNew(ProcessQueue, TokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); task.ContinueWith(OnTaskFaulted, TaskContinuationOptions.OnlyOnFaulted); task.Wait(); Logger.Debug("Task finished."); } catch (RedisException ex) { Logger.ErrorException("An error occured while attempting to access Redis.", ex); } finally { if (TokenSource != null) { TokenSource.Cancel(); TokenSource.Dispose(); } } Logger.Info("Application ending."); return -1; // Return a non-zero code so AppHarbor restarts the worker }
private static void ScheduleNewJob(Project proj) { var cts = new System.Threading.CancellationTokenSource(); var token = cts.Token; var jobInfo = CreateJob_DaylightFactor(); //var jobInfo = CreateJob_AnnualDaylight(); try { jobInfo.SetJobSubFolderPath("round1/test"); jobInfo.SetJobName("A new daylight simulation"); // run a job var task = jobInfo.RunJobOnCloud(proj, (s) => Console.WriteLine(s), token); //cts.CancelAfter(60000); var scheduledJob = task.Result; // watch status var watchTask = scheduledJob.WatchJobStatusAsync((s) => Console.WriteLine(s), token); watchTask.Wait(); Console.WriteLine($"Canceled check: {token.IsCancellationRequested}"); cts.Dispose(); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); //throw; } }
static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); cts.CancelAfter(1000); AsyncFactory.GetIntAsync(cts.Token).ContinueWith((task) => { //We get the response. //So dispose the CancellationTokenSource //so that it is not going to signal. cts.Dispose(); if (task.Status == TaskStatus.RanToCompletion) { Console.WriteLine(task.Result); } else if (task.Status == TaskStatus.Canceled) { Console.WriteLine("The task has been canceled."); } else { Console.WriteLine("An error has been occurred. Details:"); Console.WriteLine(task.Exception.InnerException.Message); } }); Console.ReadLine(); }
public void CancelAfterDisposed() { var cts = new CancellationTokenSource(); cts.CancelAfter(1000); cts.Dispose(); Thread.Sleep(2000); Assert.IsFalse(cts.IsCancellationRequested); }
private static CancellationTokenSource ResetCancellationTokenSource(System.Threading.CancellationTokenSource cts) { if (cts != null) { cts.Dispose(); } // Create a new cancellation token source so that can cancel all the tokens again return(new CancellationTokenSource()); }
public bool Enqueue(T item) { lock (queue) { if (this.Count > 0) { var _item = queue.Dequeue(); if (_item.WaitForResponse) { L4Logger.Info("Can not insert item must WaitForResponse => " + _item.MethodName); queue.Enqueue(_item); item.Dispose(); return(false); } else { } } if (closing || null == item) { return(false); } queue.Enqueue(item); CancellationTokenSource?.Dispose(); CancellationTokenSource = new System.Threading.CancellationTokenSource(); System.Threading.Tasks.Task.Run(async delegate { await Task.Delay(item.CommandTimeSpan, CancellationTokenSource.Token); if (!CancellationTokenSource.IsCancellationRequested) { if (ObjectTimeout != null) { if (queue.Count > 0) { var value = (T)queue.Dequeue(); L4Logger.Info(string.Format("object Dequeue Timeout method {0} guid {1} ", value.MethodName, value.guid)); value.Dispose(); ObjectTimeout.Invoke(value); } } } }); L4Logger.Info(string.Format("item inserted {0} Timeout {1} WaitForResponse {2} guid {3}", item.MethodName, item.CommandTimeSpan, item.WaitForResponse, item.guid)); if (queue.Count == 1) { // wake up any blocked dequeue Monitor.PulseAll(queue); } item = null; return(true); } }
public void CanCancelDownloadFilesAsync() { var token = new CancellationTokenSource(); QDownloader = GetQueueDownloader(); token.Cancel(); Func<Task> act = () => QDownloader.DownloadAsync(GetDefaultSpec(), token.Token); act.ShouldThrow<OperationCanceledException>(); token.Dispose(); }
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { UpdateUi(); ((BackgroundWorker)sender).Dispose(); _backgroundWorkerCTS?.Dispose(); if (!string.IsNullOrEmpty(_runParameters.ResultsAutoSaveFileName)) { AutoSaveResults(_runParameters.ResultsAutoSaveFileName); } }
private void SearchClick(object sender, EventArgs e) { try { _view.ClearingFields(); if(_model.SearchResultsList.Count!=0) _model.SearchResultsList.Clear(); UpdateModel(); tokenSource = new CancellationTokenSource(); ct = tokenSource.Token; searchingThread = Task.Factory.StartNew(() => { tokenSource.Token.ThrowIfCancellationRequested(); this.MakeRegexMask(); Regex regMask = new Regex(_model.FileMask, RegexOptions.IgnoreCase); DirectoryInfo di = new DirectoryInfo(_model.Drive); if (!di.Exists) throw new Exception("Выбранный Вами локальный диск не найден или Вам отказано в доступе"); _view.ShowInfoMessage("Поиск начат!"); Searching(di, regMask); int count = _model.SearchResultsList.Count; string endResult; if (_model.IsResults()) endResult = String.Format("Поиск завершен. Найдено {0} файлов", count); else endResult = String.Format("Поиск завершен.По Вашему запросу ничего не найдено"); _view.ShowInfoMessage(endResult); },tokenSource.Token); } catch(Exception ex) { _view.ShowErrorMessage(ex.Message); } finally { if (searchingThread.IsCanceled || searchingThread.IsCompleted || searchingThread.IsFaulted) { searchingThread.Dispose(); tokenSource.Dispose(); } } }
private async Task PostWebServiceDataAsync(string mediaId) { try { Random random = new Random(); int r = random.Next(); string requestUrl = "http://replatform.cloudapp.net:8000/userAction?uuid={0}&type={1}&media_id={2}&from={3}&to={4}&r={5}"; string userid = App.gDeviceName; requestUrl = String.Format(requestUrl, userid, App.gDeviceType, mediaId, App.NavigationRoadmap.GetFrom(), App.NavigationRoadmap.GetTo(), r); HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); filter.AutomaticDecompression = true; HttpClient httpClient = new HttpClient(filter); CancellationTokenSource cts = new CancellationTokenSource(); filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.Default; filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default; Uri resourceUri; if (!Uri.TryCreate(requestUrl.Trim(), UriKind.Absolute, out resourceUri)) { return; } HttpResponseMessage response = await httpClient.GetAsync(resourceUri).AsTask(cts.Token); string jsonText = await Helpers.GetResultAsync(response, cts.Token); GetPostUserActionResult(jsonText); if (filter != null) { filter.Dispose(); filter = null; } if (httpClient != null) { httpClient.Dispose(); httpClient = null; } if (cts != null) { cts.Dispose(); cts = null; } } catch (Exception) { } }
public async Task ShutdownActionInvokedWithCancellationToken() { // Arrange Mock<IAsynchronousDelay> delay = new Mock<IAsynchronousDelay>(); bool shutdownActionInvoked = false; AsynchronousIntervalTimer timer = new AsynchronousIntervalTimer(delay.Object, TimeSpan.FromMilliseconds(PretendDelayInMilliseconds), false); CancellationTokenSource source = new CancellationTokenSource(); // Act await timer.ExecuteAsync(ct => Task.FromResult(false), source.Token, () => shutdownActionInvoked = true); // Assert Assert.IsTrue(shutdownActionInvoked); source.Dispose(); }
static void Main() { int[] nums = Enumerable.Range(0, 10000000).ToArray(); CancellationTokenSource cts = new CancellationTokenSource(); // Use ParallelOptions instance to store the CancellationToken ParallelOptions po = new ParallelOptions(); po.CancellationToken = cts.Token; po.MaxDegreeOfParallelism = System.Environment.ProcessorCount; Console.WriteLine("Press any key to start. Press 'c' to cancel."); Console.ReadKey(); // Run a task so that we can cancel from another thread. Task.Factory.StartNew(() => { while(true) { if (Console.ReadKey().KeyChar == 'c') { cts.Cancel(); Console.WriteLine("press any key to exit"); } } }); try { Parallel.ForEach(nums, po, (num) => { double d = Math.Sqrt(num); Console.WriteLine("{0} on {1}", d, Thread.CurrentThread.ManagedThreadId); po.CancellationToken.ThrowIfCancellationRequested(); }); } catch (OperationCanceledException e) { Console.WriteLine(e.Message); } finally { cts.Dispose(); } Console.ReadKey(); }
public async Task ConnectAsync(string url) { await DisconnectAsync(); _disconnectToken = new CancellationTokenSource(); var cancelToken = _disconnectToken.Token; _webSocket = new ClientWebSocket(); _webSocket.Options.KeepAliveInterval = TimeSpan.Zero; await _webSocket.ConnectAsync(new Uri(url), cancelToken); _host = url; if (_isDebug) RaiseOnDebugMessage(DebugMessageType.Connection, $"Connected."); OnConnect(); _lastHeartbeat = DateTime.UtcNow; _task = Task.Factory.ContinueWhenAll(CreateTasks(), x => { if (_isDebug) RaiseOnDebugMessage(DebugMessageType.Connection, $"Disconnected."); //Do not clean up until all tasks have ended OnDisconnect(); _disconnectToken.Dispose(); _disconnectToken = null; _wasDisconnectedUnexpected = false; //Clear send queue _heartbeatInterval = 0; _lastHeartbeat = DateTime.MinValue; _webSocket.Dispose(); _webSocket = null; byte[] ignored; while (_sendQueue.TryDequeue(out ignored)) { } if (_isConnected) { _isConnected = false; RaiseDisconnected(_wasDisconnectedUnexpected); } _task = null; }); }
static async Task Main() { var serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(); serviceCollection.AddNatsRpc(config => config.AddContractHandler <ITest, Test>()); var provider = serviceCollection.BuildServiceProvider(); var serviceHost = provider.GetRequiredService <IHostedService>(); var cts = new System.Threading.CancellationTokenSource(); var token = cts.Token; await serviceHost.StartAsync(token); var connectionFactory = new ConnectionFactory(); var proxyFactory = new ProxyFactory(connectionFactory); var proxy = proxyFactory.Create <ITest>(ProxyOptions.Default); var response = proxy.Echo("Hello World!"); System.Console.WriteLine($"Echo response: {response}"); proxy.Rpc("RPC", 100); var responseTask = proxy.EchoAsync("Hello World Async!"); System.Console.WriteLine($"Echo response: {await responseTask}"); await proxy.RpcAsync("Async RPC", 101); var model = new ITest.TestModel() { Name = "TEST" }; var echoModel = await proxy.EchoModel(model); System.Console.WriteLine($"Async echo model: {echoModel.Name}"); System.Console.ReadLine(); proxy.Dispose(); await serviceHost.StopAsync(token); cts.Cancel(); cts.Dispose(); }
static void Main(string[] args) { var nji = new NjiApi(); nji.CleanTempDir(); var cst = new CancellationTokenSource(); Console.CancelKeyPress += (o, e) => { // todo: support cancellation // cst.Cancel(); }; if (args.Length < 1) Usage(); try { string subcommand = args[0]; if (subcommand == "install") nji.InstallAsync(args.Skip(1), cst.Token).Wait(); else if (subcommand == "update") nji.UpdateAsync(cst.Token).Wait(); else Usage(); } catch (AggregateException ex) { if (ex.InnerException is NjiException || ex.InnerException is IOException) { Console.WriteLine(); Console.WriteLine("Error: " + ex.InnerException.Message); Environment.Exit(1); } else { throw; } } finally { cst.Dispose(); } nji.CleanTempDir(); }
/// <summary> /// Actual logic for actually making asynchronous webrequest and retrieving the response for the server. /// </summary> /// <param name="typeArg"></param> /// <param name="httpMethod"></param> /// <param name="resource"></param> /// <returns>A task of RestResponse.</returns> protected virtual Task <RestResponse> GetResponseInternalAsync(Type typeArg) { _isAsyncTimeout = false; HttpWebRequest webRequest = CreateHttpWebRequest(); WriteRequestStream(webRequest); _cancellationTokenSource = new System.Threading.CancellationTokenSource(); System.Threading.CancellationToken cancellationToken = _cancellationTokenSource.Token; Task <WebResponse> result = Task.Factory.FromAsync(webRequest.BeginGetResponse, asyncResult => webRequest.EndGetResponse(asyncResult), (object)webRequest); ThreadPool.RegisterWaitForSingleObject((result as IAsyncResult).AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), webRequest, TimeOut, true); cancellationToken.Register((state) => { webRequest.Abort(); }, webRequest); return(result.ContinueWith((task) => { _cancellationTokenSource.Dispose(); if (task.IsFaulted) { const string message = "An exception has occured, get more detail in inner-exception"; if (_isAsyncTimeout) { return CreateResponse(typeArg, null, new RestException(0, message, null, new Exception("The operation has timed out"))); } else { var aggregateException = task.Exception.Flatten(); var innerExceptionOrAggregateException = aggregateException.InnerExceptions.Count == 1 ? aggregateException.InnerException : aggregateException; return CreateResponse(typeArg, null, new RestException(0, message, null, innerExceptionOrAggregateException)); } } else { return CreateResponse(typeArg, (HttpWebResponse)task.Result, null); } })); }
private Task<JObject> ReadConfigurationData(TimeSpan maxWaitTime,TimeSpan pollInterval) { var cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(maxWaitTime); return ReadConfigurationData(cancellationTokenSource.Token,pollInterval).ContinueWith(t => { cancellationTokenSource.Dispose(); if ( t.Exception != null ) { throw t.Exception; } return t.Result.MergeEnvironments(environmentSequence); }); }
static void PrintMatches(string digits) { var keys = Keyboard.Translate(digits); // foreach (var match in Matcher.GetWords(keys)) { // Console.WriteLine(match); // } var tokenSource = new CancellationTokenSource(); var ct = tokenSource.Token; var task = Matcher.StartGettingWords(keys, (w) => Console.WriteLine(w), ct); //tokenSource.Cancel(); try { task.Wait(); } catch (AggregateException ex) { Console.WriteLine("Task cancelled"); } finally { tokenSource.Dispose(); } }
static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; var obj1 = new CancellableObject("o1"); var obj2 = new CancellableObject("o2"); token.Register(() => obj1.Cancel1()); Console.WriteLine("And another token registration."); token.Register(() => obj1.Cancel2()); token.Register(() => obj2.Cancel1()); cts.Cancel(); cts.Dispose(); }
public async void Run() { IsRunning = true; _cts = new CancellationTokenSource(); await Task.Run(() => { try { _a(_cts.Token); }catch(OperationCanceledException e) { if(OnCancel != null) OnCancel(this, new EventArgs()); } finally { _cts.Dispose(); } }); IsRunning = false; }
public void Run() { // 執行foreach loop取消PLINQ執行,是非常簡單的,簡單的方式可以用break; //// 查詢會自動執行enumerator的Disposed,且取消 (這段不確定是不是這樣。) // 用cancellation token 可從其他的執行緒取消執行。 insert a token, 使用WithCancellation after calling AsParallel // 然後傳述 CancellationTokenSource的Token property。其他的執行去可以在token source上呼叫取消,並且throws OperationCanceledException // 取消有兩種方式 // 第一個範例說明如何取消大多由資料周遊所組成的查詢 // 第二個範例說明如何取消使用者涵是在計算時需耗費高度資源的查詢 // 範例一: int[] source = Enumerable.Range(1, 10000000).ToArray(); CancellationTokenSource cts = new CancellationTokenSource(); // 通常會在按下按鈕後,或者是某一個事件後做取消的動作 // 這在邊先開一個非同步任務作取消的觸發動作 Task.Factory.StartNew( () => this.UserClicksTheCancelButton(cts) ); int[] results = null; try { results = (from num in source.AsParallel().WithCancellation(cts.Token) where num % 3 == 0 orderby num descending select num).ToArray(); } catch (OperationCanceledException e) { Console.WriteLine(e.Message); } finally { cts.Dispose(); } // 取消的一般指引如下 // 1.如果您執行使用者委派取消,則應向 PLINQ 通知有關外部 CancellationToken 的資訊,並擲回 OperationCanceledException (externalCT)。 // 2.如果取消執行,且未擲回其他例外狀況,則您應處理 OperationCanceledException,而不是 AggregateException。 }
/// <summary> /// Sends a <paramref name="request"/> using the given <paramref name="client"/>. /// </summary> /// <param name="client">The <see cref="HttpClient"/> on which to execute the request.</param> /// <param name="eventLoop">The <see cref="EventLoop"/> on which to execute callbacks.</param> /// <param name="request">The <see cref="HttpResponseMessage"/> which to send.</param> /// <returns>Returns a <see cref="Promise{HttpResponseMessage}"/> resolving to <see cref="HttpResponseMessage"/>.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> public static CancelablePromise<HttpResponseMessage> Send(this HttpClient client, EventLoop eventLoop, HttpRequestMessage request) { // validate arguments if (client == null) throw new ArgumentNullException("client"); if (eventLoop == null) throw new ArgumentNullException("eventLoop"); if (request == null) throw new ArgumentNullException("request"); // create the cancellation token var cts = new CancellationTokenSource(); var token = cts.Token; // create the deferred var deferred = eventLoop.Defer<HttpResponseMessage>(cts.Cancel); // create a resource managed by the event loop eventLoop.TrackResource(token, Task.Run(() => { try { // send the request and retrieve the response var response = client.SendAsync(request, token).Result; // resolve the deferred if not cancelled if (!token.IsCancellationRequested) deferred.Resolve(response); } catch (Exception ex) { // something bad happened, reject the deferred if not cancelled if (!token.IsCancellationRequested) deferred.Reject(ex); } // dispose the used resources request.Dispose(); cts.Dispose(); })); // return the promise return deferred.Promise; }
private async Task ShowPanel(Label label, Control panel) { panel.BringToFront(); panel.Visible = true; label.Visible = false; panel.Focus(); var cancel = new System.Threading.CancellationTokenSource(); var token = cancel.Token; EventHandler visibleChanged = null; visibleChanged = delegate { cancel.Cancel(); }; panel.VisibleChanged += visibleChanged; var r = this.RectangleToScreen(panel.Bounds); do { try { await Task.Delay(500, token); } catch (TaskCanceledException) { break; } }while (forceShowPanel || r.Contains(Cursor.Position) || Control.MouseButtons.HasFlag(MouseButtons.Left)); panel.VisibleChanged -= visibleChanged; if (!cancel.IsCancellationRequested) { panel.Visible = false; label.Visible = true; } cancel.Dispose(); }
public void Cancel() { this.completedCallback = null; this.errorCallback = null; this.failedCallback = null; if (timeoutTokenSource != null) { try { timeoutTokenSource.Cancel(); } catch (Exception) {}; timeoutTokenSource.Dispose(); timeoutTokenSource = null; } if (this.webRequest != null) { this.webRequest.Abort(); this.webRequest = null; } }
private void DownloadCancel_Click(object sender, RoutedEventArgs e) { DownloadCancel.IsEnabled = false; ctsForDownload.Cancel(); ctsForDownload.Dispose(); }
//**************************************** /// <summary> /// Disposes of the linked cancellation token /// </summary> public void Dispose() => _LinkedSource?.Dispose();