/// <summary> /// Asynchronously performs a search and updates the observable SearchResults property. /// </summary> /// <param name="query"> The search query </param> public void SearchAndUpdateResults(string query) { if (Visible != Visibility.Visible) { return; } Task <IEnumerable <SearchElementBase> > .Factory.StartNew(() => { lock (SearchDictionary) { return(Search(query)); } }).ContinueWith((t) => { lock (_visibleSearchResults) { // deselect the last selected item if (_visibleSearchResults.Count > SelectedIndex) { _visibleSearchResults[SelectedIndex].IsSelected = false; } // clear visible results list _visibleSearchResults.Clear(); // if the search query is empty, go back to the default treeview if (string.IsNullOrEmpty(query) || query == "Search...") { foreach (var ele in BrowserRootCategories) { ele.CollapseToLeaves(); ele.SetVisibilityToLeaves(Visibility.Visible); } // hide the top result _topResult.Visibility = Visibility.Collapsed; return; } // otherwise, first collapse all foreach (var root in BrowserRootCategories) { root.CollapseToLeaves(); root.SetVisibilityToLeaves(Visibility.Collapsed); } //// if there are any results, add the top result if (t.Result.Any() && t.Result.ElementAt(0) is NodeSearchElement) { _topResult.Items.Clear(); _topResult.AddChild(new TopSearchElement(t.Result.ElementAt(0))); _topResult.SetVisibilityToLeaves(Visibility.Visible); _topResult.IsExpanded = true; } // for all of the other results, show them in their category foreach (var ele in _browserLeaves) { if (t.Result.Contains(ele)) { ele.Visibility = Visibility.Visible; ele.ExpandToRoot(); } } // create an ordered list of visible search results var baseBrowserItem = new BrowserRootElement("root"); foreach (var root in BrowserRootCategories) { baseBrowserItem.Items.Add(root); } baseBrowserItem.GetVisibleLeaves(ref _visibleSearchResults); if (_visibleSearchResults.Any()) { this.SelectedIndex = 0; _visibleSearchResults[0].IsSelected = true; } } } , TaskScheduler.FromCurrentSynchronizationContext()); // run continuation in ui thread }
protected override void HandleActivation(CompositeDisposable disposables) { IsLoading = true; Task.Run(() => { var products = new List <Stock>(); if (saftValidator?.StockFile != null) { var saft_products = saftValidator.StockFile.Stock; //create binding products foreach (var c in saft_products) { products.Add(new Stock { ProductCode = c.ProductCode, ProductDescription = c.ProductDescription, ProductNumberCode = c.ProductNumberCode, ClosingStockQuantity = c.ClosingStockQuantity, ProductCategory = c.ProductCategory.ToString(), UnitOfMeasure = c.UnitOfMeasure }); } } return(products); }).ContinueWith(async p => { var products = await p; CollectionView = new DataGridCollectionView(products) { Filter = o => { if (string.IsNullOrWhiteSpace(Filter)) { return(true); } if (o is Stock product) { if (product.ProductCode != null && product.ProductCode.Contains(Filter, StringComparison.OrdinalIgnoreCase)) { return(true); } if (product.ProductDescription != null && product.ProductDescription.Contains(Filter, StringComparison.OrdinalIgnoreCase)) { return(true); } if (product.ProductNumberCode != null && product.ProductNumberCode.Contains(Filter, StringComparison.OrdinalIgnoreCase)) { return(true); } if (product.ProductCategory != null && product.ProductCategory.Contains(Filter, StringComparison.OrdinalIgnoreCase)) { return(true); } if (product.UnitOfMeasure != null && product.UnitOfMeasure.Contains(Filter, StringComparison.OrdinalIgnoreCase)) { return(true); } } return(false); } }; CollectionView.GroupDescriptions.Add(new DataGridPathGroupDescription("ProductCategory")); IsLoading = false; this.WhenAnyValue(x => x.Filter) .Throttle(TimeSpan.FromSeconds(1)) .ObserveOn(RxApp.MainThreadScheduler) .InvokeCommand(SearchCommand) .DisposeWith(disposables); }, TaskScheduler.FromCurrentSynchronizationContext()); }
public void GetInstanceAsync_ExecutesMigrationsInBackground() { TestHelpers.RunAsyncTest(async() => { Realm realm = null; var config = (RealmConfiguration)RealmConfiguration.DefaultConfiguration; config.SchemaVersion = 1; using (var firstRealm = Realm.GetInstance(config)) { Assert.That(firstRealm.All <IntPrimaryKeyWithValueObject>().Count(), Is.Zero); } var threadId = Environment.CurrentManagedThreadId; var hasCompletedMigration = false; config.SchemaVersion = 2; config.MigrationCallback = (migration, oldSchemaVersion) => { Assert.That(Environment.CurrentManagedThreadId, Is.Not.EqualTo(threadId)); Task.Delay(300).Wait(); migration.NewRealm.Add(new IntPrimaryKeyWithValueObject { Id = 123 }); hasCompletedMigration = true; }; Exception ex = null; #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Realm.GetInstanceAsync(config) .ContinueWith(t => { if (t.IsFaulted) { ex = t.Exception; } else { realm = t.Result; } }, TaskScheduler.FromCurrentSynchronizationContext()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed var ticks = 0; while (realm == null) { await Task.Delay(100); ticks++; if (ticks > 10) { Assert.Fail("Migration should have completed by now."); } } Assert.That(ex, Is.Null); Assert.That(hasCompletedMigration); Assert.That(ticks, Is.GreaterThanOrEqualTo(2)); Assert.That(realm.All <IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(1)); realm.Dispose(); }); }
public static Task WaitWith <T>(this Task <T> @this, Task other, Action <Task <T> > ithen) { return(@this.WaitWith(other, ithen, TaskScheduler.FromCurrentSynchronizationContext())); }
public static void ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => TypedProxyTests.ServiceContract_TypedProxy_AsyncBeginEnd_Call(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: TypedProxy_AsyncBeginEnd_Call_WithSingleThreadedSyncContext timed out"); }
private async void Connect() { var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); await LoadWebSocket(scheduler); }
/// <summary> /// User has clicked button to search the log files based on the given pattern, so /// let's up an set of tasks to run this in the background so we don't lock the UI. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmdSearch_Click(object sender, RoutedEventArgs e) { this.txtblkResults.Text = ""; // clear previous results... this.cmdSearch.IsEnabled = false; // disable button until we are done: this.spinnerWait.Visibility = System.Windows.Visibility.Visible; this.spinnerWait.Spin = true; var sw = new System.Diagnostics.Stopwatch(); // start clock: sw.Restart(); // // search all the files listed in the listbox: // List<string> filenames = new List<string>(); foreach (DisplayFileName dfn in this.lstFiles.Items) filenames.Add(dfn.FullFileName); string pattern = this.txtPattern.Text; // create a task to make the call so we don't lock up the UI: Task<int> search = Task.Factory.StartNew<int>(() => { return SearchFiles(filenames, pattern); } ); // // When the search task finishes, update the UI. We another task to wait for the result // so that we don't lock up the UI waiting --- but this has to be a separate task since // any UI work must be done by the thread that owns the UI (the main thread): // Task UpdateUI = search.ContinueWith((antecedent) => { try { int hits = antecedent.Result; var timeinMS = sw.ElapsedMilliseconds; // stop clock: double time = timeinMS / 1000.0; // convert to secs: string results = string.Format("Hits:\t{0:#,##0}\nFiles:\t{1:#,##0}\nTime:\t{2:#,##0.00} secs\n", hits, lstFiles.Items.Count, time); this.txtblkResults.Text = results; } catch (AggregateException ae) { this.txtblkResults.Text = ""; ae = ae.Flatten(); foreach (Exception ex in ae.InnerExceptions) this.txtblkResults.Text += string.Format("**Error: '{0}'\n", ex.Message); } catch (Exception ex) { this.txtblkResults.Text = string.Format("**Error: '{0}'\n", ex.Message); } // reset UI: this.spinnerWait.Spin = false; this.spinnerWait.Visibility = System.Windows.Visibility.Collapsed; this.cmdSearch.IsEnabled = true; // re-enable button: }, TaskScheduler.FromCurrentSynchronizationContext() // must run on current (UI) thread: ); }
private void encryptClicked() { string password = textBox1.Text; string confirmPassword = textBox2.Text; //If fields are empty if (password.Equals("") || confirmPassword.Equals("")) { MessageBox.Show("Dont't leave it blank!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } //If password is not equal to confirm password else if (password != confirmPassword) { MessageBox.Show("Passwords don't match", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { //Encrypt content of rich text box saveFileDialog.Filter = "Textual Encrypted|*.texx"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { //Task to encrypt and save file Task <string> task = new Task <string>(() => { try { string filename = saveFileDialog.FileName; //Add "ENCRYPTED" to the start of content to be encrypted rtb_content = "ENCRYPTED" + rtb_content; //Encrypt content and save string encrypted_content = Encryptor.Encrypt(rtb_content, password); File.WriteAllText(filename, ""); StreamWriter strw = new StreamWriter(filename); strw.Write(encrypted_content); strw.Close(); strw.Dispose(); return(filename); } catch (Exception ex) { throw ex; } }); //When task is over call changeSavedState method on parent form to remove * from tab title task.ContinueWith(t => { parent.Enabled = true; parent.changeSavedState(); parent.changeTitleLabel(t.Result); this.Dispose(); }, TaskScheduler.FromCurrentSynchronizationContext()); //Handle any exceptions that occured in the task task.ContinueWith(t => { task.Exception.Handle(ex => { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); }); parent.Enabled = true; this.Dispose(); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext()); task.Start(); } } }
public static AsyncRequestObject LiveStream(Socket socket, OnNewLiveFrame NewLiveFrameCallback, CancellationTokenSource cts = null, TaskScheduler ts = null) { AsyncRequestObject aro = new AsyncRequestObject(cts); ts = ts == null?TaskScheduler.FromCurrentSynchronizationContext() : ts; BlockingCollection <LiveCompressedFrame> queueCompressed = new BlockingCollection <LiveCompressedFrame>(1); #region Streaming task aro.task = Task.Factory.StartNew(() => { byte[] bytes = null; HiResTimer t = new HiResTimer(); Int64 t1 = t.Value; Int64 frames = 0; while (!aro.CancellationToken.WaitHandle.WaitOne(0)) { bytes = IPServices.ReceiveOnSocket(socket, aro.CancellationToken, 30000, Marshal.SizeOf(typeof(DATA_FRAME_HEADER))); if (bytes != null && bytes.Length != 0) { // Full header received GCHandle pinnedPacket = GCHandle.Alloc(bytes, GCHandleType.Pinned); DATA_FRAME_HEADER dfh = (DATA_FRAME_HEADER)Marshal.PtrToStructure(pinnedPacket.AddrOfPinnedObject(), typeof(DATA_FRAME_HEADER)); pinnedPacket.Free(); // Get frame bytes = IPServices.ReceiveOnSocket(socket, aro.CancellationToken, 5000, dfh.TotalLength - Marshal.SizeOf(typeof(DATA_FRAME_HEADER))); if (bytes != null && bytes.Length != 0) { //queueCompressed.Add(new LiveCompressedFrame(dfh, bytes), aro.CancellationToken); Debug.Print(dfh.CameraID.ToString() + " " + bytes.Length.ToString()); // add code here to put frame into decoder input queue } else { break; } } else { // Server closed connection? break; } ++frames; if (frames % 100 == 0) { Int64 timeTicks = t.Value - t1; Int64 timeElapseInSeconds = timeTicks / t.Frequency; Debug.Print("Frame rate = {0}", (float)frames / (float)timeElapseInSeconds); } } //fs.Close(); }, aro.CancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default); #endregion return(aro); }
public void Execute(ExportToProjectVM vm) { vm.ProgressMinimum = 0; vm.ProgressMaximum = 1; vm.TotalProgress = 0; vm.IsIndeterminate = false; Task.Factory.StartNew(() => { var decompilationContext = new DecompilationContext { CancellationToken = cancellationToken, GetDisableAssemblyLoad = () => owner.documentTreeView.DocumentService.DisableAssemblyLoad(), }; var options = new ProjectCreatorOptions(vm.Directory, cancellationToken); options.ProjectVersion = vm.ProjectVersion; if (vm.CreateSolution) { options.SolutionFilename = vm.SolutionFilename; } options.Logger = this; options.ProgressListener = this; bool hasProjectGuid = vm.ProjectGuid.Value != null; string guidFormat = null; int guidNum = 0; if (hasProjectGuid) { string guidStr = vm.ProjectGuid.Value.ToString(); guidNum = int.Parse(guidStr.Substring(36 - 8, 8), NumberStyles.HexNumber); guidFormat = guidStr.Substring(0, 36 - 8) + "{0:X8}"; } foreach (var module in modules.OrderBy(a => a.Location, StringComparer.InvariantCultureIgnoreCase)) { var projOpts = new ProjectModuleOptions(module, vm.Decompiler, decompilationContext) { DontReferenceStdLib = vm.DontReferenceStdLib, UnpackResources = vm.UnpackResources, CreateResX = vm.CreateResX, DecompileXaml = vm.DecompileXaml, ProjectGuid = hasProjectGuid ? new Guid(string.Format(guidFormat, guidNum++)) : Guid.NewGuid(), }; if (bamlDecompiler != null) { var o = BamlDecompilerOptions.Create(vm.Decompiler); projOpts.DecompileBaml = (a, b, c, d) => bamlDecompiler.Decompile(a, b, c, o, d); } options.ProjectModules.Add(projOpts); } var creator = new MSBuildProjectCreator(options); creator.Create(); if (vm.CreateSolution) { fileToOpen = creator.SolutionFilename; } else { fileToOpen = creator.ProjectFilenames.FirstOrDefault(); } }, cancellationToken) .ContinueWith(t => { var ex = t.Exception; if (ex != null) { Error(string.Format(dnSpy_Resources.ErrorExceptionOccurred, ex)); } EmtpyErrorList(); vm.OnExportComplete(); if (!vm.ExportErrors) { dlg.Close(); if (vm.OpenProject) { OpenProject(); } } }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); }
public Form1() { InitializeComponent(); _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); }
public static Task <U> Then <T, U>(this Task <T> task, Func <T, Task <U> > asyncFunc) { if (asyncFunc == null) { throw new ArgumentNullException("asyncFunc"); } return(task.ContinueWith(t => asyncFunc(t.Result), CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext()).Unwrap()); }
public static Task Then <T>(this Task <T> task, Action <T> action) { if (action == null) { throw new ArgumentNullException("action"); } return(task.ContinueWith(t => action(t.Result), CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext())); }
public FoldChangeBindingSource(GroupComparisonModel groupComparisonModel) { _container = new Container(); GroupComparisonModel = groupComparisonModel; _taskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext()); }
/// <summary> /// Initializes a task notifier watching the specified task. /// </summary> /// <param name="task">The task to watch.</param> public NotifyTaskCompletionImplementation(Task task) { Task = task; if (task.IsCompleted) { TaskCompleted = _completedTask; return; } var scheduler = (SynchronizationContext.Current == null) ? TaskScheduler.Current : TaskScheduler.FromCurrentSynchronizationContext(); TaskCompleted = task.ContinueWith(t => { var propertyChanged = PropertyChanged; if (propertyChanged == null) { return; } propertyChanged(this, new PropertyChangedEventArgs("Status")); propertyChanged(this, new PropertyChangedEventArgs("IsCompleted")); propertyChanged(this, new PropertyChangedEventArgs("IsNotCompleted")); if (t.IsCanceled) { propertyChanged(this, new PropertyChangedEventArgs("IsCanceled")); } else if (t.IsFaulted) { propertyChanged(this, new PropertyChangedEventArgs("IsFaulted")); propertyChanged(this, new PropertyChangedEventArgs("Exception")); propertyChanged(this, new PropertyChangedEventArgs("InnerException")); propertyChanged(this, new PropertyChangedEventArgs("ErrorMessage")); } else { propertyChanged(this, new PropertyChangedEventArgs("IsSuccessfullyCompleted")); } }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler); }
public MainForm() { InitializeComponent(); this.MinimumSize = new Size(Settings.DEFAULT_WIDTH, Settings.DEFAULT_HEIGHT); SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true); centerPanel.MouseDown += Form1_MouseDown; centerPanel.MouseMove += Form1_MouseMove; centerPanel.MouseUp += Form1_MouseUp; panelRight.MouseDown += Form1_MouseDown; panelRight.MouseMove += Form1_MouseMove; panelRight.MouseUp += Form1_MouseUp; contextMenu1.MenuItems.Add(new MenuItem("LISTEN.moe Desktop Client v" + Globals.VERSION.ToString()) { Enabled = false }); Settings.LoadSettings(); //Write immediately after loading to flush any new default settings Settings.WriteSettings(); cts = new CancellationTokenSource(); ct = cts.Token; #pragma warning disable CS4014 CheckForUpdates(new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext())); #pragma warning restore CS4014 StartUpdateAutochecker(); this.MouseWheel += Form1_MouseWheel; this.Icon = Properties.Resources.icon; notifyIcon1.ContextMenu = contextMenu2; notifyIcon1.Icon = Properties.Resources.icon; Task.Run(async() => await LoadFavSprite(heartFav)).Wait(); if (Settings.Get <bool>(Setting.ThumbnailButton)) { button = new ThumbnailToolBarButton(Properties.Resources.pause_ico, "Pause"); button.Click += async(_, __) => await TogglePlayback(); TaskbarManager.Instance.ThumbnailToolBars.AddButtons(this.Handle, button); } Connect(); string stream = Settings.Get <StreamType>(Setting.StreamType) == StreamType.Jpop ? JPOP_STREAM : KPOP_STREAM; player = new WebStreamPlayer(stream); player.Play(); renderLoop = Task.Run(() => { while (!ct.IsCancellationRequested) { centerPanel.Invalidate(); Thread.Sleep(33); } }); ReloadScale(); ReloadSettings(); this.SizeChanged += MainForm_SizeChanged; UpdatePanelExcludedRegions(); }
private void UpdateFileStatusListView(bool updateCausedByFilter = false) { if (_itemsDictionary == null || !_itemsDictionary.Any()) { HandleVisibility_NoFilesLabel_FilterComboBox(filesPresent: false); } else { EnsureSelectedIndexChangeSubscription(); HandleVisibility_NoFilesLabel_FilterComboBox(filesPresent: true); } FileStatusListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); var previouslySelectedItems = new List <GitItemStatus>(); if (updateCausedByFilter) { foreach (ListViewItem Item in FileStatusListView.SelectedItems) { previouslySelectedItems.Add((GitItemStatus)Item.Tag); } if (DataSourceChanged != null) { DataSourceChanged(this, new EventArgs()); } } FileStatusListView.BeginUpdate(); FileStatusListView.ShowGroups = _itemsDictionary != null && _itemsDictionary.Count > 1; FileStatusListView.Groups.Clear(); FileStatusListView.Items.Clear(); if (_itemsDictionary != null) { var clientSizeWidth = AppSettings.TruncatePathMethod == "compact" || AppSettings.TruncatePathMethod == "trimstart"; var fileNameOnlyMode = AppSettings.TruncatePathMethod == "fileNameOnly"; var list = new List <ListViewItem>(); foreach (var pair in _itemsDictionary) { ListViewGroup group = null; if (!String.IsNullOrEmpty(pair.Key)) { var groupName = ""; if (pair.Key == CombinedDiff.Text) { groupName = CombinedDiff.Text; } else { groupName = _DiffWithParent.Text + " " + GetDescriptionForRevision(pair.Key); } group = new ListViewGroup(groupName); group.Tag = pair.Key; FileStatusListView.Groups.Add(group); } foreach (var item in pair.Value) { if (_filter.IsMatch(item.Name)) { var text = item.Name; if (clientSizeWidth) { // list-item has client width, so we don't need horizontal scrollbar (which is determined by this text width) text = string.Empty; } else if (fileNameOnlyMode) { // we need to put filename in list-item text -> then horizontal scrollbar // will have proper width (by the longest filename, and not all path) text = PathFormatter.FormatTextForFileNameOnly(item.Name, item.OldName); text = AppendItemSubmoduleStatus(text, item); } var listItem = new ListViewItem(text, group); listItem.ImageIndex = GetItemImageIndex(item); if (item.SubmoduleStatus != null && !item.SubmoduleStatus.IsCompleted) { var capturedItem = item; item.SubmoduleStatus.ContinueWith((task) => listItem.ImageIndex = GetItemImageIndex(capturedItem), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext()); } if (previouslySelectedItems.Contains(item)) { listItem.Selected = true; } listItem.Tag = item; list.Add(listItem); } } } FileStatusListView.Items.AddRange(list.ToArray()); } if (updateCausedByFilter == false) { FileStatusListView_SelectedIndexChanged(); if (DataSourceChanged != null) { DataSourceChanged(this, new EventArgs()); } if (SelectFirstItemOnSetItems) { SelectFirstVisibleItem(); } } FileStatusListView_SizeChanged(null, null); FileStatusListView.SetGroupState(ListViewGroupState.Collapsible); FileStatusListView.EndUpdate(); }
protected virtual bool OnBackButtonPressed() { var application = RealParent as Application; if (application == null || this == application.MainPage) { return(false); } var canceled = false; EventHandler handler = (sender, args) => { canceled = true; }; application.PopCanceled += handler; Navigation.PopModalAsync().ContinueWith(t => { throw t.Exception; }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext()); application.PopCanceled -= handler; return(!canceled); }
#pragma warning disable 1998 // considered for removal async void ScrollTo(object group, object item, ScrollToPosition toPosition, bool shouldAnimate, bool includeGroup = false, bool previouslyFailed = false) #pragma warning restore 1998 { ScrollViewer viewer = GetScrollViewer(); if (viewer == null) { RoutedEventHandler loadedHandler = null; loadedHandler = async(o, e) => { List.Loaded -= loadedHandler; // Here we try to avoid an exception, see explanation at bottom await Dispatcher.RunIdleAsync(args => { ScrollTo(group, item, toPosition, shouldAnimate, includeGroup); }); }; List.Loaded += loadedHandler; return; } var templatedItems = TemplatedItemsView.TemplatedItems; Tuple <int, int> location = templatedItems.GetGroupAndIndexOfItem(group, item); if (location.Item1 == -1 || location.Item2 == -1) { return; } object[] t = templatedItems.GetGroup(location.Item1).ItemsSource.Cast <object>().ToArray(); object c = t[location.Item2]; // scroll to desired item with animation if (shouldAnimate && ScrollToItemWithAnimation(viewer, c)) { return; } double viewportHeight = viewer.ViewportHeight; var semanticLocation = new SemanticZoomLocation { Item = c }; // async scrolling await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { switch (toPosition) { case ScrollToPosition.Start: { List.ScrollIntoView(c, ScrollIntoViewAlignment.Leading); return; } case ScrollToPosition.MakeVisible: { List.ScrollIntoView(c, ScrollIntoViewAlignment.Default); return; } case ScrollToPosition.End: case ScrollToPosition.Center: { var content = (FrameworkElement)List.ItemTemplate.LoadContent(); content.DataContext = c; content.Measure(new Windows.Foundation.Size(viewer.ActualWidth, double.PositiveInfinity)); double tHeight = content.DesiredSize.Height; if (toPosition == ScrollToPosition.Center) { semanticLocation.Bounds = new Rect(0, viewportHeight / 2 - tHeight / 2, 0, 0); } else { semanticLocation.Bounds = new Rect(0, viewportHeight - tHeight, 0, 0); } break; } } }); // Waiting for loaded doesn't seem to be enough anymore; the ScrollViewer does not appear until after Loaded. // Even if the ScrollViewer is present, an invoke at low priority fails (E_FAIL) presumably because the items are // still loading. An invoke at idle sometimes work, but isn't reliable enough, so we'll just have to commit // treason and use a blanket catch for the E_FAIL and try again. try { List.MakeVisible(semanticLocation); } catch (Exception) { if (previouslyFailed) { return; } Task.Delay(1).ContinueWith(ct => { ScrollTo(group, item, toPosition, shouldAnimate, includeGroup, true); }, TaskScheduler.FromCurrentSynchronizationContext()).WatchForError(); } }
public Task <TResult> ContinueWhenAll <TAntecedentResult, TResult>( Task <TAntecedentResult>[] tasks, Func <Task <TAntecedentResult>[], TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { //Console.WriteLine("ContinueWhenAll " + new { tasks.Length, scheduler, Thread.CurrentThread.ManagedThreadId }); var t = new __Task <TResult> { InternalStart = null }; var cstart = 0; var cstop = 0; #region ContinueWhenAll_yield Action ContinueWhenAll_yield = delegate { // how can we pass array of tasks to background? //Console.WriteLine("ContinueWhenAll_yield " + new { scheduler }); #region GUI if (scheduler != null) { var r = continuationFunction(tasks); t.InternalSetCompleteAndYield(r); return; } #endregion // X:\jsc.svn\examples\javascript\appengine\Test\AppEngineFirstEverWebServiceTask\AppEngineFirstEverWebServiceTask\ApplicationWebService.cs var xfunction = continuationFunction; var MethodType = typeof(FuncOfTaskOfObjectArrayToObject).Name; #region MethodToken var MethodToken = ((__MethodInfo)xfunction.Method).InternalMethodToken; if (xfunction.Target != null) { if (xfunction.Target != Native.self) { // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs Delegate InternalTaskExtensionsScope_function = (xfunction.Target as dynamic).InternalTaskExtensionsScope_function; if (InternalTaskExtensionsScope_function == null) { var message = "inline scope sharing not yet implemented"; Console.WriteLine(message); throw new InvalidOperationException(message); } MethodToken = ((__MethodInfo)InternalTaskExtensionsScope_function.Method).InternalMethodToken; } } #endregion #region xdata___string // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs dynamic xdata___string = new object(); // how much does this slow us down? // connecting to a new scope, we need a fresh copy of everything // we can start with strings foreach (ExpandoMember nn in Expando.Of(InternalInlineWorker.__string).GetMembers()) { if (nn.Value != null) { xdata___string[nn.Name] = nn.Value; } } #endregion // is this correct? // OBSOLETE ! needs more tests. what about scope sharing? var w = new global::ScriptCoreLib.JavaScript.DOM.Worker( InternalInlineWorker.GetScriptApplicationSourceForInlineWorker() //global::ScriptCoreLib.JavaScript.DOM.Worker.ScriptApplicationSourceForInlineWorker ); var TaskArray = tasks.Select(k => new { k.Result }).ToArray(); Console.WriteLine(new { TaskArray = TaskArray.Length }); //Debugger.Break(); #region postMessage w.postMessage( new { InternalInlineWorker.InternalThreadCounter, MethodToken, MethodType, //state = state, // pass the result for reconstruction // task[0].Result TaskArray, __string = (object)xdata___string } , e => { // what kind of write backs do we expect? // for now it should be console only // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs dynamic zdata = e.data; #region AtWrite string AtWrite = zdata.AtWrite; if (!string.IsNullOrEmpty(AtWrite)) { Console.Write(AtWrite); } #endregion #region __string var zdata___string = (object)zdata.__string; if (zdata___string != null) { #region __string dynamic target = InternalInlineWorker.__string; var m = Expando.Of(zdata___string).GetMembers(); foreach (ExpandoMember nn in m) { Console.WriteLine("Worker has sent changes " + new { nn.Name }); target[nn.Name] = nn.Value; } #endregion } #endregion #region yield dynamic yield = zdata.yield; if ((object)yield != null) { object value = yield.value; //Console.WriteLine("__Task.InternalStart inner complete " + new { yield = new { value } }); t.InternalSetCompleteAndYield((TResult)value); //w.terminate(); } #endregion } ); #endregion InternalInlineWorker.InternalThreadCounter++; }; #endregion #region ContinueWhenAll_yield foreach (__Task <TAntecedentResult> item in tasks) { cstart++; //Console.WriteLine("ContinueWhenAll before ContinueWith " + new { cstart, tasks.Length, Thread.CurrentThread.ManagedThreadId }); item.ContinueWith( task => { cstop++; //Console.WriteLine("ContinueWhenAll ContinueWith yield " + new { cstop, tasks.Length, Thread.CurrentThread.ManagedThreadId }); if (cstop == tasks.Length) { //Console.WriteLine("before ContinueWhenAll_yield"); ContinueWhenAll_yield(); //Console.WriteLine("after ContinueWhenAll_yield"); } }, // just for the watchdog scheduler: TaskScheduler.FromCurrentSynchronizationContext() ); } #endregion return(t); }
/// <summary> /// Standart constrcutor which adds a listener to PropertyChanged /// </summary> /// <param name="uiStateModel"></param> private GameEndViewModel(UiStateModel uiStateModel) { taskFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext()); this.uiStateModel = uiStateModel; PropertyChanged += shown; }
public void RefreshAndSearchAsync() { this.ClearSearchResults(); this.SearchState = PackageSearchState.SYNCING; Task <IEnumerable <PackageManagerSearchElementViewModel> > .Factory.StartNew(RefreshAndSearch).ContinueWith((t) => { lock (SearchResults) { ClearSearchResults(); foreach (var result in t.Result) { this.AddToSearchResults(result); } this.SearchState = HasNoResults ? PackageSearchState.NORESULTS : PackageSearchState.RESULTS; } } , TaskScheduler.FromCurrentSynchronizationContext()); // run continuation in ui thread }
private void CreateMDBCommandExecute() { if (IsCopying) return; IsCopying = true; Stopwatch sw = new Stopwatch(); sw.Start(); bool hasError = false; IsShowingCopyProgress = true; string guid = Guid.NewGuid().ToString(); string fileName = _project.FileName.Replace(".prj", String.Empty); Task.Factory.StartNew( () => { Project newProject = ContactTracing.ImportExport.ImportExportHelper.CreateNewOutbreak(Country, _appCulture, @"Projects\VHF\" + fileName + "_" + guid + ".prj", @"Projects\VHF\" + fileName + "_" + guid + ".mdb", _outbreakDate.Ticks.ToString(), _outbreakName); ContactTracing.ImportExport.FormCopier formCopier = new ImportExport.FormCopier(_project, newProject, _caseForm); formCopier.SetProgressBar += formCopier_SetProgressBar; formCopier.SetMaxProgressBarValue += formCopier_SetMaxProgressBarValue; try { formCopier.Copy(); } catch (Exception ex) { hasError = true; System.Windows.Forms.MessageBox.Show(ex.Message, "Exception", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } finally { formCopier.SetProgressBar -= formCopier_SetProgressBar; formCopier.SetMaxProgressBarValue -= formCopier_SetMaxProgressBarValue; } }, System.Threading.CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith( delegate { ProgressValue = 0; IsCopying = false; sw.Stop(); if (hasError) { CopyStatus = "Copying halted due to error."; System.IO.File.Delete(@"Projects\VHF\" + fileName + "_" + guid + ".prj"); System.IO.File.Delete(@"Projects\VHF\" + fileName + "_" + guid + ".mdb"); } else { CopyStatus = "Finished copying data to mdb file. Elapsed time: " + sw.Elapsed.TotalMinutes.ToString("F1") + " minutes."; } }, TaskScheduler.FromCurrentSynchronizationContext()); }
public void Start(string filePath) { _context.NotifyPluginsHost(NotificationType.ShowBusyIndicator, 1); var isActive = _mainGuiModel.DumperSettings.IsActive; var filesCount = _mainGuiModel.Files.Count; _mainGuiModel.DumperSettings.IsActive = false; var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(() => { var itemsList = JsonHelper.DeserializeFromFile <IList <BaseInfo> >(filePath, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, }); return(itemsList); }).ContinueWith(task => { if (task.IsFaulted) { if (task.Exception != null) { task.Exception.Flatten().Handle(ex => { new ExceptionLogger().LogExceptionToFile(ex, AppMessenger.LogFile); AppMessenger.Messenger.NotifyColleagues("ShowException", ex); return(true); }); } _context.NotifyPluginsHost(NotificationType.HideBusyIndicator, 1); return; } try { var itemsList = task.Result; if (itemsList == null || !itemsList.Any()) { return; } clearAllData(); _context.NotifyPluginsHost(NotificationType.ResetAll, 0); var count = 0; foreach (var item in itemsList) { var baseInfo = item; baseInfo.ReceivedId = IdGenerator.GetId(); switch (baseInfo.InfoType) { case InfoType.Command: var command = (Command)baseInfo; command.SetCommandStatistics(); _context.ProfilerData.Commands.Add(command); break; case InfoType.CommandConnection: _context.ProfilerData.Connections.Add((CommandConnection)baseInfo); break; case InfoType.CommandResult: _context.ProfilerData.Results.Add((CommandResult)baseInfo); break; case InfoType.CommandTransaction: _context.ProfilerData.Transactions.Add((CommandTransaction)baseInfo); break; } if (count++ % 100 == 0) { DispatcherHelper.DoEvents(); } } } finally { _mainGuiModel.DumperSettings.IsActive = isActive; _context.NotifyPluginsHost(NotificationType.HideBusyIndicator, 1); _context.NotifyPluginsHost(NotificationType.Reset, filesCount); } }, taskScheduler); }
/// <summary> /// Initializes a new instance of the <see cref="MainWindow"/> class. /// </summary> /// <param name="builder">Builder.</param> /// <param name="handle">Handle.</param> private MainWindow(Builder builder, IntPtr handle) : base(handle) { builder.Autoconnect(this); DeleteEvent += OnDeleteEvent; this.UIThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext(); this.ViewportWidget = new GLWidget { CanFocus = true, SingleBuffer = false, ColorBPP = 24, DepthBPP = 24, AccumulatorBPP = 24, Samples = 4, GLVersionMajor = 3, GLVersionMinor = 3, GraphicsContextFlags = GraphicsContextFlags.Default }; this.ViewportWidget.Events |= EventMask.ButtonPressMask | EventMask.ButtonReleaseMask | EventMask.KeyPressMask | EventMask.KeyReleaseMask; this.ViewportWidget.Initialized += delegate { // Initialize all OpenGL rendering parameters this.RenderingEngine.Initialize(); Idle.Add(OnIdleRenderFrame); }; this.ViewportWidget.ButtonPressEvent += OnViewportButtonPressed; this.ViewportWidget.ButtonReleaseEvent += OnViewportButtonReleased; this.ViewportWidget.ConfigureEvent += OnViewportConfigured; this.RenderingEngine = new ViewportRenderer(this.ViewportWidget); this.ViewportAlignment.Add(this.ViewportWidget); this.ViewportAlignment.ShowAll(); // Add a staggered idle handler for adding enumerated items to the interface //Timeout.Add(1, OnIdle, Priority.DefaultIdle); Idle.Add(OnIdle, Priority.DefaultIdle); this.AboutButton.Clicked += OnAboutButtonClicked; this.PreferencesButton.Clicked += OnPreferencesButtonClicked; this.GameExplorerTreeView.RowExpanded += OnGameExplorerRowExpanded; this.GameExplorerTreeView.RowActivated += OnGameExplorerRowActivated; this.GameExplorerTreeView.Selection.Changed += OnGameExplorerSelectionChanged; this.GameExplorerTreeView.ButtonPressEvent += OnGameExplorerButtonPressed; this.GameExplorerTreeSorter.SetSortFunc(1, SortGameExplorerRow); this.GameExplorerTreeSorter.SetSortColumnId(1, SortType.Descending); this.ExportQueueTreeView.ButtonPressEvent += OnExportQueueButtonPressed; this.ExtractItem.Activated += OnExtractContextItemActivated; this.ExportItem.Activated += OnExportItemContextItemActivated; this.OpenItem.Activated += OnOpenContextItemActivated; this.CopyItem.Activated += OnCopyContextItemActivated; this.QueueItem.Activated += OnQueueContextItemActivated; this.RemoveQueueItem.Activated += OnQueueRemoveContextItemActivated; this.FiletreeBuilder = new ExplorerBuilder ( new ExplorerStore ( this.GameExplorerTreeStore, this.GameExplorerTreeFilter, this.GameExplorerTreeSorter ) ); this.FiletreeBuilder.PackageGroupAdded += OnPackageGroupAdded; this.FiletreeBuilder.PackageEnumerated += OnPackageEnumerated; this.FiletreeBuilder.Start(); /* * Set up item control sections to default states */ EnableControlPage(ControlPage.None); }
private void Navigate(Uri oldValue, Uri newValue, NavigationType navigationType) { Debug.WriteLine("Navigating from '{0}' to '{1}'", oldValue, newValue); // set IsLoadingContent state SetValue(IsLoadingContentPropertyKey, true); // cancel previous load content task (if any) // note: no need for thread synchronization, this code always executes on the UI thread if (this.tokenSource != null) { this.tokenSource.Cancel(); this.tokenSource = null; } // push previous source onto the history stack (only for new navigation types) if (oldValue != null && navigationType == NavigationType.New) { this.history.Push(oldValue); } object newContent = null; if (newValue != null) { // content is cached on uri without fragment var newValueNoFragment = NavigationHelper.RemoveFragment(newValue); if (navigationType == NavigationType.Refresh || !this.contentCache.TryGetValue(newValueNoFragment, out newContent)) { var localTokenSource = new CancellationTokenSource(); this.tokenSource = localTokenSource; // load the content (asynchronous!) var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); var task = this.ContentLoader.LoadContentAsync(newValue, this.tokenSource.Token); task.ContinueWith(t => { try { if (t.IsCanceled || localTokenSource.IsCancellationRequested) { Debug.WriteLine("Cancelled navigation to '{0}'", newValue); } else if (t.IsFaulted) { // raise failed event var failedArgs = new NavigationFailedEventArgs { Frame = this, Source = newValue, Error = t.Exception.InnerException, Handled = false }; OnNavigationFailed(failedArgs); // if not handled, show error as content newContent = failedArgs.Handled ? null : failedArgs.Error; SetContent(newValue, navigationType, newContent, true); } else { newContent = t.Result; if (ShouldKeepContentAlive(newContent)) { // keep the new content in memory this.contentCache[newValueNoFragment] = newContent; } SetContent(newValue, navigationType, newContent, false); } } finally { // clear global tokenSource to avoid a Cancel on a disposed object if (this.tokenSource == localTokenSource) { this.tokenSource = null; } // and dispose of the local tokensource localTokenSource.Dispose(); } }, scheduler); return; } } // newValue is null or newContent was found in the cache SetContent(newValue, navigationType, newContent, false); }
private void OnBorrowClosing(object sender, DialogClosingEventArgs args) { if (Equals(args.Parameter, false)) { return; } if (args.Parameter is TextBox) { args.Session.UpdateContent(new PleaseWaitView()); TextBox txtName = (TextBox)args.Parameter; int number; var name = txtName.Text.Trim(); var tryParse = Int32.TryParse(name, out number); if (tryParse) { if (number > SelectedBook.AvailableQuantity) { args.Cancel(); args.Session.UpdateContent(new OkMessageDialog() { DataContext = "Borrow quantity can't exceed available quantity." }); return; } if (number < 1) { args.Cancel(); args.Session.UpdateContent(new OkMessageDialog() { DataContext = "Minimum quantity is 1." }); return; } } Task.Run(() => { if (tryParse) { _oldSelectedTeacher = SelectedTeacher; var bookSearch = _context.TeacherBorrowedBooks.FirstOrDefault(c => c.Teacher.Id == SelectedTeacher.Id && c.Book.Id == SelectedBook.Id); bool isFind = bookSearch != null; if (!isFind) { var newBorrowedbook = new TeacherBorrowedBook { Teacher = SelectedTeacher, Book = SelectedBook, QuantityBorrowed = number, DateBorrowed = DateTime.Now.Date, }; //SelectedBook.AvailableQuantity = _context.TeacherBorrowedBooks.Add(newBorrowedbook); _context.SaveChanges(); } else { var borBook = _context.TeacherBorrowedBooks.FirstOrDefault(c => c.Teacher.Id == SelectedTeacher.Id && c.Book.Id == SelectedBook.Id); if (borBook != null) { borBook.QuantityBorrowed = borBook.QuantityBorrowed + number; //SelectedBook.AvailableQuantity -= number; //_unitOfWork.TeacherBorrowedBook.ModifyBorrowedBook(borBook); } } var newBorrowedBook = new TeacherBorrowedBook(); //var borrewdBook = _context.TeacherBorrowedBooks. var bookList = _context.TeacherBorrowedBooks.Where(c => c.Book.Id == SelectedBook.Id).ToList(); int quantityBorrowed = 0; foreach (var book in bookList) { quantityBorrowed += book.QuantityBorrowed; } SelectedBook.AvailableQuantity = SelectedBook.Quantity - (quantityBorrowed + SelectedBook.Damaged + SelectedBook.Outdated); _context.SaveChangesAsync(); } }).ContinueWith((t, _) => { LoadData(); Messenger.Default.Send(new NewBookUpdate()); SelectedTeacher = _oldSelectedTeacher; }, null, TaskScheduler.FromCurrentSynchronizationContext()); } }
public static void Display(string content, string sound, Action click) { if (Instance._taskPopup == null || Instance._taskPopup.IsCompleted) { Instance._taskPopup = Task.Factory.StartNew(() => { }); } Instance._taskPopup = Instance._taskPopup.ContinueWith(t => Instance.DisplayAsync(new object[] { content, sound, click }), TaskScheduler.FromCurrentSynchronizationContext()); }
private void btnOKOnline_Click(object sender, EventArgs e) { if (this.uxOnlineProjects.SelectedItem != null) { this.btnInstall.Enabled = false; downloadDialog.Show(); IPackage pack = this.uxOnlineProjects.SelectedItem as IPackage; var inactiveExtensions = App.Extensions.Where(a => a.IsActive == false).ToArray(); Task task = Task.Factory.StartNew(delegate { IEnumerable <PackageDependency> dependency = pack.Dependencies; if (dependency.Count() > 0) { foreach (PackageDependency dependentPackage in dependency) { App.ProgressHandler.Progress(null, 0, "Downloading Dependency " + dependentPackage.Id); downloadDialog.ShowDownloadStatus(dependentPackage); downloadDialog.SetProgressBarPercent(0); var dependentpack = packages.Install(dependentPackage.Id); if (dependentpack == null) { string message = "We cannot download " + dependentPackage.Id + " Please make sure you are connected to the Internet."; MessageBox.Show(message); return; } } } this.App.ProgressHandler.Progress(null, 0, "Downloading " + pack.Title); downloadDialog.ShowDownloadStatus(pack); downloadDialog.SetProgressBarPercent(0); this.packages.Install(pack.Id); }); task.ContinueWith(delegate(Task t) { this.App.ProgressHandler.Progress(null, 0, "Installing " + pack.Title); this.UpdateInstalledProjectsList(); // Load the extension. App.RefreshExtensions(); IEnumerable <PackageDependency> dependency = pack.Dependencies; App.ProgressHandler.Progress(null, 50, "Installing " + pack.Title); // Activate the extension(s) that was installed. var extensions = App.Extensions.Where(a => !inactiveExtensions.Contains(a) && a.IsActive == false); if (extensions.Count() > 0 && !App.EnsureRequiredImportsAreAvailable()) { return; } foreach (var item in extensions) { item.TryActivate(); } this.App.ProgressHandler.Progress(null, 0, "Ready."); downloadDialog.Visible = false; }, TaskScheduler.FromCurrentSynchronizationContext()); } }