public static IYubicoResponse Validate(IEnumerable<string> urls, string userAgent) { var tasks = new List<Task<IYubicoResponse>>(); var cancellation = new CancellationTokenSource(); foreach (var url in urls) { var thisUrl = url; var task = new Task<IYubicoResponse>(() => DoVerify(thisUrl, userAgent), cancellation.Token); task.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted); tasks.Add(task); task.Start(); } while (tasks.Count != 0) { // TODO: handle exceptions from the verify task. Better to be able to propagate cause for error. var completed = Task.WaitAny(tasks.Cast<Task>().ToArray()); var task = tasks[completed]; tasks.Remove(task); if (task.Result != null) { cancellation.Cancel(); return task.Result; } } return null; }
private void ConnectToRabbit(ConnectionFactory connectionfactory, string rabbitMqExchangeName) { if (1 == Interlocked.Exchange(ref _resource, 1)) { return; } _rabbitConnection = new RabbitConnection(connectionfactory, rabbitMqExchangeName); _rabbitConnection.OnMessage( wrapper => OnReceived(wrapper.Key, wrapper.Id, wrapper.Messages)); _rabbitConnectiontask = _rabbitConnection.StartListening(); _rabbitConnectiontask.ContinueWith( t => { Interlocked.Exchange(ref _resource, 0); ConnectToRabbit(connectionfactory, rabbitMqExchangeName); } ); _rabbitConnectiontask.ContinueWith( t => { Interlocked.Exchange(ref _resource, 0); ConnectToRabbit(connectionfactory, rabbitMqExchangeName); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default ); }
protected override void OnMouseClick(MouseEventArgs e) { if(_cts != null) { _cts.Cancel(); _cts = null; } else { Text = @"Operation running"; _cts = new CancellationTokenSource(); var task = new Task<int>(() => Sum(2000, _cts.Token), _cts.Token); task.Start(); // UI 작업에서는 SynchronizationTaskScheduler를 사용해야 합니다. task.ContinueWith(antecedent => Text = "Result:" + antecedent.Result, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, _syncContextTaskScheduler); task.ContinueWith(antecedent => Text = "Operation canceled", CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, _syncContextTaskScheduler); task.ContinueWith(antecedent => Text = "Operation faulted", CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, _syncContextTaskScheduler); } base.OnMouseClick(e); }
public void StartAnalysis() { var task = new Task<StoreReport>(RunAnalysis); task.ContinueWith(t => t != null ? (Report = new StoreAnalysisModel(t.Result)) : null,CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext()); task.ContinueWith(t => AnalyzerException = t.Exception,CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext()); task.Start(); }
internal static void HandleOnCompleted (Task task, Action continuation) { var scontext = SynchronizationContext.Current; if (scontext != null) task.ContinueWith (l => scontext.Post (cont => ((Action) cont) (), continuation), TaskContinuationOptions.ExecuteSynchronously); else task.ContinueWith (l => continuation (), TaskContinuationOptions.ExecuteSynchronously); }
internal static void HandleOnCompleted (Task task, Action continuation, bool continueOnSourceContext) { if (continueOnSourceContext && SynchronizationContext.Current != null) { task.ContinueWith (new SynchronizationContextContinuation (continuation, SynchronizationContext.Current)); } else { task.ContinueWith (new ActionContinuation (continuation)); } }
internal static void HandleOnCompleted (Task task, Action continuation, bool continueOnSourceContext, InstanceReference instanceReference, IAsyncSetThis thisSetter) { if (continueOnSourceContext && SynchronizationContext.Current != null) { task.ContinueWith(new SynchronizationContextContinuation(continuation, SynchronizationContext.Current, instanceReference, thisSetter)); } else { task.ContinueWith (new ActionContinuation (continuation)); } }
private void button2_Click(object sender, EventArgs e) { Coder coder = new Coder(_point_State_color, new TimeSpan(0,2,0)); CancellationToken token = _tokenSrcCancel.Token; Task task = new Task( () => coder.Code(token), token); task.ContinueWith(coding_exception_handler, TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(coding_done_handler, TaskContinuationOptions.OnlyOnRanToCompletion); task.Start(); }
internal static void HandleOnCompleted (Task task, Action continuation, bool continueOnSourceContext) { if (continueOnSourceContext && SynchronizationContext.Current != null) { // Capture source context var ctx = SynchronizationContext.Current; task.ContinueWith (l => ctx.Post (cont => ((Action) cont) (), continuation), TaskContinuationOptions.ExecuteSynchronously); } else { task.ContinueWith ((l, cont) => ((Action) cont) (), continuation, TaskContinuationOptions.ExecuteSynchronously); } }
static void ContinuationTask() { Task t1 = new Task(DoOnFirst); Task t2 = t1.ContinueWith(DoOnSecond); Task t3 = t1.ContinueWith(DoOnSecond); Task t4 = t2.ContinueWith(DoOnSecond); Task t5 = t1.ContinueWith(DoOnError, TaskContinuationOptions.OnlyOnFaulted); t1.Start(); Thread.Sleep(5000); }
static void Main(string[] args) { // create a cancellation token source CancellationTokenSource tokenSource = new CancellationTokenSource(); // create the antecedent task Task task = new Task(() => { // write out a message Console.WriteLine("Antecedent running"); // wait indefinately on the token wait handle tokenSource.Token.WaitHandle.WaitOne(); // handle the cancellation exception tokenSource.Token.ThrowIfCancellationRequested(); }, tokenSource.Token); // create a selective continuation Task neverScheduled = task.ContinueWith(antecedent => { // write out a message Console.WriteLine("This task will never be scheduled"); }, tokenSource.Token); // create a bad selective contination Task badSelective = task.ContinueWith(antecedent => { // write out a message Console.WriteLine("This task will never be scheduled"); }, tokenSource.Token, TaskContinuationOptions.OnlyOnCanceled, TaskScheduler.Current); // create a good selective contiuation Task continuation = task.ContinueWith(antecedent => { // write out a message Console.WriteLine("Continuation running"); }, TaskContinuationOptions.OnlyOnCanceled); // start the task task.Start(); // prompt the user so they can cancel the token Console.WriteLine("Press enter to cancel token"); Console.ReadLine(); // cancel the token source tokenSource.Cancel(); // wait for the good continuation to complete continuation.Wait(); // wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine(); }
static void Main(string[] args) { // get the processor count for the system int procCount = System.Environment.ProcessorCount; // create a custom scheduler CustomScheduler scheduler = new CustomScheduler(procCount); Console.WriteLine("Custom scheduler ID: {0}", scheduler.Id); Console.WriteLine("Default scheduler ID: {0}", TaskScheduler.Default.Id); // create a cancellation token source CancellationTokenSource tokenSource = new CancellationTokenSource(); // create a task Task task1 = new Task(() => { Console.WriteLine("Task {0} executed by scheduler {1}", Task.CurrentId, TaskScheduler.Current.Id); // create a child task - this will use the same // scheduler as its parent Task.Factory.StartNew(() => { Console.WriteLine("Task {0} executed by scheduler {1}", Task.CurrentId, TaskScheduler.Current.Id); }); // create a child and specify the default scheduler Task.Factory.StartNew(() => { Console.WriteLine("Task {0} executed by scheduler {1}", Task.CurrentId, TaskScheduler.Current.Id); }, tokenSource.Token, TaskCreationOptions.None, TaskScheduler.Default); }); // start the task using the custom scheduler task1.Start(scheduler); // create a continuation - this will use the default scheduler task1.ContinueWith(antecedent => { Console.WriteLine("Task {0} executed by scheduler {1}", Task.CurrentId, TaskScheduler.Current.Id); }); // create a continuation using the custom scheduler task1.ContinueWith(antecedent => { Console.WriteLine("Task {0} executed by scheduler {1}", Task.CurrentId, TaskScheduler.Current.Id); }, scheduler); }
static void Main(string[] args) { // create a token source CancellationTokenSource tokenSource = new CancellationTokenSource(); // create the antecedent task Task<int> task1 = new Task<int>(() => { // wait for the token to be cancelled tokenSource.Token.WaitHandle.WaitOne(); // throw the cancellation exception tokenSource.Token.ThrowIfCancellationRequested(); // return the result - this code will // never be reached but is required to // satisfy the compiler return 100; }, tokenSource.Token); // create a continuation // *** BAD CODE *** Task task2 = task1.ContinueWith((Task<int> antecedent) => { // read the antecedent result without checking // the status of the task Console.WriteLine("Antecedent result: {0}", antecedent.Result); }); // create a continuation, but use a token Task task3 = task1.ContinueWith((Task<int> antecedent) => { // this task will never be executed }, tokenSource.Token); // create a continuation that checks the status // of the antecedent Task task4 = task1.ContinueWith((Task<int> antecedent) => { if (antecedent.Status == TaskStatus.Canceled) { Console.WriteLine("Antecedent cancelled"); } else { Console.WriteLine("Antecedent Result: {0}", antecedent.Result); } }); // prompt the user and cancel the token Console.WriteLine("Press enter to cancel token"); Console.ReadLine(); tokenSource.Cancel(); // wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine(); }
static void Main(string[] args) { Class1 d = new Class1(Path.GetFullPath(System.Environment.CurrentDirectory + "/../")); Console.Read(); var Start = new Task(() => start()); Start.ContinueWith(t => Contiute1_1()) .ContinueWith(t => Contiute1_2()); var task2_1 = Start.ContinueWith(t => Contiute2_1()); var task2_2 = task2_1.ContinueWith(t => Contiute2_2()); Start.RunSynchronously(); Console.WriteLine("end"); Console.ReadKey(); }
public void Add(ITextFile textFile) { Task task = new Task(() => ProduceFrom(textFile)); task.ContinueWith(HandleFileProcessed); producerTasks.TryAdd(task, textFile); task.Start(); }
protected override void OnResume() { base.OnResume(); Task startupWork = new Task(() => { Log.Debug(TAG, "Performing some startup work that takes a bit of time."); Thread.Sleep(2000); //Task.Delay(5000); // Simulate a bit of startup work. Log.Debug(TAG, "Working in the background - important stuff."); }); startupWork.ContinueWith(t => { Log.Debug(TAG, "Work is finished - start Activity1."); var userSettings = new AndroidUserSettings(); if (string.IsNullOrEmpty(userSettings.GetUserSetting("language"))) { StartActivity(new Intent(Application.Context, typeof(LanguageInitializer))); } else { StartActivity(new Intent(Application.Context, typeof(MainActivity))); } }, TaskScheduler.FromCurrentSynchronizationContext()); startupWork.Start(); }
//called when data for any output pin is requested public void Evaluate(int SpreadMax) { if(FInput.IsChanged) { FOutput.SliceCount = FInput.SliceCount; for (int i = 0; i < FInput.SliceCount; i++) { var r = new TRes(); r.host = FInput[i]; r.idx = i; r.Resolved = false; var t = new Task<TRes>(() => _GetHostByName(r)); var c = t.ContinueWith((res) => { if(res.Result.ips != null) { FOutput[res.Result.idx].SliceCount = res.Result.ips.Length; for(int j = 0; j<res.Result.ips.Length;j++) { FOutput[res.Result.idx][j] = res.Result.ips[j]; } } else FOutput[res.Result.idx].SliceCount = 0; },TaskContinuationOptions.OnlyOnRanToCompletion); t.Start(); } } //FLogger.Log(LogType.Debug, "Logging to Renderer (TTY)"); }
/// <summary> /// Initializes a task notifier watching the specified task. /// </summary> /// <param name="task"> /// The task to watch. /// </param> /// <param name="scheduler"> /// The task scheduler that should be used. /// </param> public NotifyTaskCompletion(Task task, TaskScheduler scheduler) { _task = task; if (task.IsCompleted) { return; } _taskCompleted = task.ContinueWith(t => { NotifyPropertyChanged(() => Status); NotifyPropertyChanged(() => IsCompleted); NotifyPropertyChanged(() => IsNotCompleted); if (t.IsCanceled) { NotifyPropertyChanged(() => IsCanceled); } else if (t.IsFaulted) { NotifyPropertyChanged(() => IsFaulted); NotifyPropertyChanged(() => Exception); NotifyPropertyChanged(() => InnerException); NotifyPropertyChanged(() => ErrorMessage); } else { NotifyPropertyChanged(() => IsSuccessfullyCompleted); } }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler); }
public void DoSearch() { SearchInfo searchInfo = new SearchInfo(); MainWindowViewModel.SearchInfoProperties.SaveTo(searchInfo, viewModel); if (string.IsNullOrEmpty(searchInfo.FamilyName) && string.IsNullOrEmpty(searchInfo.GivenName)) { viewModel.PeopleResults.Clear(); return; } // Cancel any previous searches cancellation.Cancel(); cancellation = new CancellationTokenSource(); searchTask = InitialTask(); MainWindowViewModel.SearchStatusProperty.SetValue(viewModel, ""); // Do the search off the UI thread. searchTask = searchTask.ContinueWith<IEnumerable<Person>>( previous => StartSearch(searchInfo), cancellation.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default) // Update the ViewModel with the search results on the UI thread. .ContinueWith( UpdateResults, cancellation.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext()); }
public TaskAsyncResult(Task task, AsyncCallback callback) { if (task != null) { task.ContinueWith(t => callback(this)); } }
public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null) : base(channelSettings, serviceSettings) { this.appleSettings = channelSettings; certificate = this.appleSettings.Certificate; certificates = new X509CertificateCollection(); if (appleSettings.AddLocalAndMachineCertificateStores) { var store = new X509Store(StoreLocation.LocalMachine); certificates.AddRange(store.Certificates); store = new X509Store(StoreLocation.CurrentUser); certificates.AddRange(store.Certificates); } certificates.Add(certificate); if (this.appleSettings.AdditionalCertificates != null) foreach (var addlCert in this.appleSettings.AdditionalCertificates) certificates.Add(addlCert); //Start our cleanup task taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning); taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted); taskCleanup.Start(); }
public AsyncResult(AsyncCallback callback, object state, Task task) { _state = state; _task = task; _completedSynchronously = _task.IsCompleted; _task.ContinueWith(t => callback(this), TaskContinuationOptions.ExecuteSynchronously); }
public void ActivationSched_NewTask_ContinueWith_Wrapped() { TaskScheduler scheduler = masterScheduler.GetWorkItemGroup(context).TaskRunner; Task<Task> wrapped = new Task<Task>(() => { output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Task t0 = new Task(() => { output.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.AreEqual(scheduler, TaskScheduler.Current, "TaskScheduler.Current #1"); }); Task t1 = t0.ContinueWith(task => { Assert.IsFalse(task.IsFaulted, "Task #1 Faulted=" + task.Exception); output.WriteLine("#2 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.AreEqual(scheduler, TaskScheduler.Current, "TaskScheduler.Current #2"); }); t0.Start(scheduler); return t1; }); wrapped.Start(scheduler); bool ok = wrapped.Unwrap().Wait(TimeSpan.FromSeconds(2)); Assert.IsTrue(ok, "Finished OK"); }
private void button1_Click(object sender, EventArgs e) { _maxTasks++; var data = ""; label1.Text = $"Tasks: {_completedTasks} of {_maxTasks}"; progressBar1.Maximum += 1; if (progressBar1.Maximum == progressBar1.Value) { progressBar1.Maximum = 0; progressBar1.Value = 0; } var t = new Task(() => { data = GetData(); }); var t2 = t.ContinueWith((previousTask) => { _completedTasks++; progressBar1.Value += 1; listBox1.Items.Insert(0, data); }, TaskScheduler.FromCurrentSynchronizationContext()); t.Start(); }
internal static void HandleOnCompleted (Task task, Action continuation, bool continueOnSourceContext, bool manageContext) { if (continueOnSourceContext && SynchronizationContext.Current != null && SynchronizationContext.Current.GetType () != typeof (SynchronizationContext)) { task.ContinueWith (new SynchronizationContextContinuation (continuation, SynchronizationContext.Current)); } else { IContinuation cont; Task cont_task; if (continueOnSourceContext && !TaskScheduler.IsDefault) { cont_task = new Task (TaskActionInvoker.Create (continuation), null, CancellationToken.None, TaskCreationOptions.None, null); cont_task.SetupScheduler (TaskScheduler.Current); cont = new SchedulerAwaitContinuation (cont_task); } else { cont_task = null; cont = new AwaiterActionContinuation (continuation); } // // This is awaiter continuation. For finished tasks we get false result and need to // queue the continuation otherwise the task would block // if (task.ContinueWith (cont, false)) return; if (cont_task == null) { cont_task = new Task (TaskActionInvoker.Create (continuation), null, CancellationToken.None, TaskCreationOptions.None, null); cont_task.SetupScheduler (TaskScheduler.Current); } cont_task.Schedule (true); } }
private static Task ToApm(Task task, AsyncCallback callback, object state) { if (task == null) { throw new ArgumentNullException("task"); } var tcs = new TaskCompletionSource<object>(state); task.ContinueWith( t => { if (t.IsFaulted) { tcs.TrySetException(t.Exception.InnerExceptions); } else if (t.IsCanceled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(null); } if (callback != null) { callback(tcs.Task); } }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); return tcs.Task; }
public static void Main() { Task<Int32[]> parent = new Task<Int32[]>(() => { var results = new Int32[3]; // Create an array for the results // This tasks creates and starts 3 child tasks new Task(() => results[0] = Sum(100), TaskCreationOptions.AttachedToParent).Start(); new Task(() => results[1] = Sum(200), TaskCreationOptions.AttachedToParent).Start(); new Task(() => results[2] = Sum(300), TaskCreationOptions.AttachedToParent).Start(); // Returns a reference to the array // (even though the elements may not be initialized yet) return results; }); // When the parent and its children have // run to completion, display the results var cwt = parent.ContinueWith(childTask => Array.ForEach(childTask.Result, Console.WriteLine)); Console.WriteLine("1. Ready"); // Start the parent Task so it can start its children parent.Start(); Console.WriteLine("2. Run"); cwt.Wait(); }
protected override void OnReceivedMessage(Message message) { var action = new Action(() => ProcessMessage(message)); var task = new Task(action); task.ContinueWith(MarkTaskAsComplete, TaskContinuationOptions.ExecuteSynchronously); task.Start(); }
/// <summary> /// Blocks the calling thread to pump messages until a task has completed. /// </summary> /// <param name="untilCompleted">The task that must complete to break out of the message loop.</param> public void PumpMessages(Task untilCompleted) { this.VerifyState(); this.pumping = true; try { // Arrange to wake up immediately when the task completes. untilCompleted.ContinueWith( _ => { lock (this.messageQueue) { Monitor.Pulse(this.messageQueue); } }, TaskScheduler.Default); // Now run the message loop until the task completes. while (!untilCompleted.IsCompleted) { this.TryOneWorkItem(); } } finally { this.pumping = false; } }
public Task Preform(CancellationToken token, TimeSpan repeatDelay) { _token = token; var task = new Task(t => { while (!_token.IsCancellationRequested) { try { Operation(); } catch (Exception e) { _logger.Fatal("Exception occurred in Main Task", e); } _token.WaitHandle.WaitOne(repeatDelay); } //end while _logger.Debug("Outside Main While Loop"); }, _token); task.ContinueWith(t => { _logger.Debug("Main Task Thread Completed"); if (t.Exception != null) _logger.Fatal("Exception in main task", t.Exception); }); task.Start(); _logger.Debug("Task Started"); return task; }