public static Task RunAsync(Action action, CoreDispatcher dispatcher = null) { if (action == null) { return Task.FromResult((object)null); } try { dispatcher = dispatcher ?? CoreApplication.MainView.CoreWindow.Dispatcher; return dispatcher.RunAsync( CoreDispatcherPriority.Normal, new DispatchedHandler(action)).AsTask() .ContinueWith( t => { if (t.IsFaulted && t.Exception != null) { CoreEventSource.Log.LogVerbose( "Got an exception from an action using the UI dispatcher: " + t.Exception.ToString()); } }); } catch (Exception exception) { CoreEventSource.Log.LogVerbose("Got an exception from an action using the UI dispatcher: " + exception); return Task.FromResult((object)null); } }
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { if (PropertyChanged == null) { return; } _dispatcher?.RunAsync(CoreDispatcherPriority.Normal, () => PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName))); }
private void Source_Updated(object sender, object s) { try { _dispatcher?.RunAsync(CoreDispatcherPriority.Normal, () => { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value))); }); } catch (Exception) { _source.Updated -= Source_Updated; } }
public AnalysisViewModel(INavigationService navigationService, IMainCommandBar commandBar) { this._navigationService = navigationService; this.AnalystDataList = new ObservableCollection <Robot.AnalystData>(); this._commandBar = commandBar; Messenger.Default.Register <SecurityListLoadedMessage>(this, (msg) => { this.SecurityList = msg.SecurityList.Where(s => s.AlgoTrade).ToList(); }); this.StartAnalyst = new RelayCommand(() => { this._analyst = new Robot.Analyst(new Robot.AnalystStrategy(), SecurityList); this._analyst.Run(); }); SelectSecurityCmd = new RelayCommand <object>((parameter) => { Windows.UI.Xaml.Controls.ItemClickEventArgs e = (Windows.UI.Xaml.Controls.ItemClickEventArgs)parameter; Robot.AnalystData selected = (Robot.AnalystData)e.ClickedItem; this._navigationService.NavigateTo("AnalysisDetails", _candles[selected.Sec]); }); Messenger.Default.Register <ShowDataMessage>(this, (msg) => { _candles = msg.Сandles; dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { AnalystDataList.Clear(); foreach (AnalystData data in msg.AnalystDatalist) { this.AnalystDataList.Add(data); } }); }); }
public async void StartListening(CoreDispatcher dispatcher) { if (Gamepad.Gamepads.Any()) { _gamePad = Gamepad.Gamepads.First(); } Gamepad.GamepadAdded += Gamepad_GamepadAdded; Gamepad.GamepadRemoved += Gamepad_GamepadRemoved; while (true) { await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (_gamePad != null) { var reading = _gamePad.GetCurrentReading(); var thisJoyStick = new Point(reading.LeftThumbstickX, reading.LeftThumbstickY); if (_lastJoyStick.HasValue && (_lastJoyStick.Value.X != thisJoyStick.X || _lastJoyStick.Value.Y != thisJoyStick.Y)) { if ((Math.Abs(thisJoyStick.X) < 0.05) && (Math.Abs(thisJoyStick.Y) < 0.05)) { JoyStickUpdated?.Invoke(_gamePad, new Point(0, 0)); } else { JoyStickUpdated?.Invoke(_gamePad, thisJoyStick); } } _lastJoyStick = thisJoyStick; _lastReading = reading; } }); await Task.Delay(TimeSpan.FromMilliseconds(250)); } }
private static Task <int?> PlatformShow(string title, string description, List <string> buttons) { // TODO: MessageDialog only supports two buttons if (buttons.Count == 3) { throw new NotSupportedException("This platform does not support three buttons"); } tcs = new TaskCompletionSource <int?>(); MessageDialog dialog = new MessageDialog(description, title); foreach (string button in buttons) { dialog.Commands.Add(new UICommand(button, null, dialog.Commands.Count)); } dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { try { // PlatformSetResult will cancel the task, resulting in an exception dialogResult = dialog.ShowAsync(); var result = await dialogResult; if (!tcs.Task.IsCompleted) { tcs.SetResult((int)result.Id); } } catch (TaskCanceledException) { if (!tcs.Task.IsCompleted) { tcs.SetResult(null); } } }); return(tcs.Task); }
protected virtual async Task <Boolean> OnHandleException(Exception exception) { Boolean flag = false; Boolean hasThreadAccess = DispatcherHelper.UIDispatcher.HasThreadAccess; if (DispatcherHelper.UIDispatcher == null || hasThreadAccess) { Boolean flag1 = await this.ProcessException(exception); flag = flag1; } else { CoreDispatcher uIDispatcher = DispatcherHelper.UIDispatcher; Int32 num = 0; await uIDispatcher.RunAsync((CoreDispatcherPriority)num, () => this.ProcessException(exception)); } Boolean flag2 = flag; return(flag2); }
internal void Run(IAsyncAction action, CoreDispatcher uiDispatcher) { bool cont = true; AppTaskResult?lastResult = null; while (cont) { var task = TaskStack.Pop(); object data; bool success = task(Parameter, action, lastResult, out data); lastResult = new AppTaskResult(success, data, lastResult); cont = (SuccessFallbackLimit == -1 || SuccessFallbackLimit > CurrentLevel) && TaskStack.Count > 0; CurrentLevel++; } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed if (action.Status != AsyncStatus.Canceled) { uiDispatcher.RunAsync(CoreDispatcherPriority.High, () => { CompletedCallback(lastResult.Value); }); } #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed }
/// <summary> /// Reloads the cache of the drives and removes the item explorer view so the user needs to select a drive again to access explorer items. /// </summary> private void ReloadCache() { CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; Debug.WriteLine(" + Reloading drives."); IsReloadButtonEnabled = false; new Thread(async() => { await App.Current.CacheHelper.UpdateDriveCache(); //A call to the UI thread is needed because of the properties that are being set. await dispatcher.RunAsync(CoreDispatcherPriority.High, () => { DriveList = App.Current.CacheHelper.CurrentUserCache.Drives; IsReloadButtonEnabled = true; // Reset the current and cached list so we don't get an exception. ExplorerItemsList = null; App.Current.MediaItemList = null; }); }).Start(); }
public OOBENetworkPage() { InitializeComponent(); _oobeNetworkPageDispatcher = Window.Current.Dispatcher; NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged; _rootFrame = Window.Current.Content as Frame; NavigationCacheMode = NavigationCacheMode.Enabled; DataContext = LanguageManager.GetInstance(); Loaded += async(sender, e) => { await _oobeNetworkPageDispatcher.RunAsync(CoreDispatcherPriority.Low, async() => { DirectConnectControl.SetUpDirectConnection(); await NetworkControl.RefreshWiFiListViewItemsAsync(true); }); }; }
public OOBENetwork() { this.InitializeComponent(); OOBENetworkPageDispatcher = Window.Current.Dispatcher; NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged; NetworkControl.NetworkConnected += NetworkGrid_NetworkConnected; this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled; this.DataContext = LanguageManager.GetInstance(); this.Loaded += async(sender, e) => { await OOBENetworkPageDispatcher.RunAsync(CoreDispatcherPriority.Low, async() => { NetworkControl.SetupDirectConnection(); await NetworkControl.RefreshWifiListViewItemsAsync(true); }); }; }
public void AddMessage(object message) { var ignored = _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var paragraph = message as Paragraph; if (paragraph != null) { _view.AddParagraph(paragraph); return; } var inline = message as Inline; if (inline != null) { _view.AddInline(inline); return; } _view.AddString(message.ToString()); }); }
public static async Task <T> RunTaskAsync <T>(this CoreDispatcher dispatcher, Func <Task <T> > func, CoreDispatcherPriority priority = CoreDispatcherPriority.High) { var taskCompletionSource = new TaskCompletionSource <T>(); async void TaskCompletionCallback() { try { taskCompletionSource.SetResult(await func().ConfigureAwait(false)); } catch (Exception ex) { taskCompletionSource.SetException(ex); } } await dispatcher.RunAsync(priority, TaskCompletionCallback); return(await taskCompletionSource.Task.ConfigureAwait(false)); }
public bool RequestMainThreadAction(Action action, bool maskExceptions = true) { if (_uiDispatcher.HasThreadAccess) { action(); return(true); } _uiDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (maskExceptions) { ExceptionMaskedAction(action); } else { action(); } }); return(true); }
public async Task ShowLoadingDialogAsync(string?message = null) { // Be sure no other dialog is open. await HideLoadingDialogAsync(); loadingDialog = new LoadingDialog { Text = message ?? Strings.LoadingLabel }; CoreApplicationView coreWindow = CoreApplication.MainView; // Dispatcher needed to run on UI Thread CoreDispatcher dispatcher = coreWindow.CoreWindow.Dispatcher; // RunAsync all of the UI info. await dispatcher.RunAsync(CoreDispatcherPriority.High, async() => { await loadingDialog.ShowAsync(); }); }
public MainPage() { this.InitializeComponent(); // This is a static public property that allows downstream pages to get a handle to the MainPage instance // in order to call methods that are in this class. Current = this; MainPageDispatcher = Window.Current.Dispatcher; NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged; this.NavigationCacheMode = NavigationCacheMode.Enabled; this.DataContext = LanguageManager.GetInstance(); timerInt = ThreadPoolTimer.CreatePeriodicTimer(GetStatTime, TimeSpan.FromSeconds(60)); timer = new DispatcherTimer(); timer.Tick += timer_Tick; timer.Interval = TimeSpan.FromSeconds(20); this.Loaded += async(sender, e) => { await MainPageDispatcher.RunAsync(CoreDispatcherPriority.Low, () => { UpdateBoardInfo(); UpdateNetworkInfo(); UpdateDateTime(); UpdateConnectedDevices(); timer.Start(); }); }; this.Unloaded += (sender, e) => { timer.Stop(); }; }
private void PeerWatcher_Added(PeerWatcher sender, PeerInformation peerInfo) { var ignored = messageDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (availablePeers) { noPeersFound.Visibility = Visibility.Collapsed; availablePeers.Add(new AvailablePeer(peerInfo)); // Don't overlap NFC text, only show this if the ListView is enabled if (foundPeers.IsEnabled) { directions.Visibility = Visibility.Visible; } } }); }
public async Task StopPreviewAsync(CoreDispatcher dispatcher) { // Stop the preview try { this.isPreviewing = false; await this.mediaCapture.StopPreviewAsync(); } catch (Exception ex) { Debug.WriteLine("Exception when stopping the preview: {0}", ex.ToString()); } await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Cleanup the UI this.previewControl.Source = null; // Allow the device screen to sleep now that the preview is stopped displayRequest.RequestRelease(); }); }
protected async void OnPropertyChanged([CallerMemberName] string propertyName = "") { if (PropertyChanged != null) { if (CoreDispatcher == null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } else { if (CoreDispatcher.HasThreadAccess) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } else { await CoreDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => PropertyChanged(this, new PropertyChangedEventArgs(propertyName))); } } } }
private IDisposable ScheduleOnDispatcherNow <TState>(TState state, Func <IScheduler, TState, IDisposable> action) { try { Interlocked.CompareExchange(ref _dispatcher, CoreApplication.Views.FirstOrDefault()?.Dispatcher, null); } catch (Exception ex) { // Ignore } if (_dispatcher == null || _dispatcher.HasThreadAccess) { return(action(this, state)); } var d = new SingleAssignmentDisposable(); var dispatchResult = _dispatcher.RunAsync( Priority, () => { if (!d.IsDisposed) { try { d.Disposable = action(this, state); } catch (Exception ex) { RaiseUnhandledException(ex); } } }); return(StableCompositeDisposable.Create( d, Disposable.Create(() => dispatchResult.Cancel()))); }
// NotifyPropertyChanged will raise the PropertyChanged event, // passing the source property that is being updated. public async void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { try { CoreDispatcher dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher; await dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); }); } catch (Exception ex) { while (ex != null) { Debug.WriteLine(ex.Message); ex = ex.InnerException; } } } }
// NotifyPropertyChanged will raise the PropertyChanged event, // passing the source property that is being updated. public async void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { try { CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; await dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); }); } catch (Exception ex) { while (ex != null) { Debug.WriteLine(ex.Message); ex = ex.InnerException; } } } }
/// <summary> /// Handle background task completion. /// </summary> /// <param name="task">The task that is reporting completion.</param> /// <param name="e">Arguments of the completion report.</param> private async void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) { ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; Object profile = localSettings.Values["InternetProfile"]; Object adapter = localSettings.Values["NetworkAdapterId"]; await NetworkStatusWithInternetPresentDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if ((profile != null) && (adapter != null)) { //If internet profile has changed, display the new internet profile if ((string.Equals(profile.ToString(), internetProfile, StringComparison.Ordinal) == false) || (string.Equals(adapter.ToString(), networkAdapter, StringComparison.Ordinal) == false)) { internetProfile = profile.ToString(); networkAdapter = adapter.ToString(); rootPage.NotifyUser("Internet Profile changed\n" + "=================\n" + "Current Internet Profile : " + internetProfile, NotifyType.StatusMessage); } } }); }
/// <summary> /// Runs the provided <see cref="Func{TResult}"/> on a <see cref="CoreDispatcher"/> in normal priority. /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="dispatcher"></param> /// <param name="func"></param> /// <returns></returns> public static async Task <TResult> RunNormalAsync <TResult>( this CoreDispatcher dispatcher, Func <TResult> func) { var source = new TaskCompletionSource <TResult>(); await dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { try { source.SetResult(func()); } catch (Exception error) { source.SetException(error); } }); return(await source.Task); }
private async void OnNowPlayingItemChanged(object sender, NowPlayingChangedEventArgs e) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { var metadata = e.NewItem?.File; if (metadata == null) { return; } NowPlayingItem = e.NewItem; CheckFavorite(); NowPlayingTitle = metadata.Title; NowPlayingArtist = metadata.Artist; NowPlayingAlbum = metadata.Album; NowPlayingTotalTime = metadata.Duration; // Update cover, if available CoverImage = new ThumbnailTag { Fallback = "Album,AlbumPlaceholder", AlbumName = metadata.Album, ArtistName = metadata.Artist, ThumbnailPath = metadata.Path, }; if (!string.IsNullOrWhiteSpace(NowPlayingTitle)) { DesktopTitleViewConfiguration.SetTitleBarText( string.Format(CommonSharedStrings.NowPlayingTitle, NowPlayingTitle)); } else { DesktopTitleViewConfiguration.SetTitleBarText(CommonSharedStrings.NowPlayingEmptyTitle); } //Call LrcAutoSearch on playlist item changed await LrcAutoSearch(); }); }
private async void ContSpeechRecognizer_HypothesisGenerated( SpeechRecognizer sender, SpeechRecognitionHypothesisGeneratedEventArgs args) { await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { //Logger.Log(args.Hypothesis.Text); switch (args.Hypothesis.Text) { case "maximize": ApplicationView.GetForCurrentView().TryEnterFullScreenMode(); break; case "minimize": ApplicationView.GetForCurrentView().ExitFullScreenMode(); break; case "zoom in": ApplicationView.GetForCurrentView().TryResizeView(new Size(Width = this.ActualWidth * 1.5, Height = this.ActualHeight * 1.5)); ++zoomCount; break; case "zoom out": if (zoomCount > 0) { ApplicationView.GetForCurrentView().TryResizeView(new Size(Width = this.ActualWidth * 0.66, Height = this.ActualHeight * 0.66)); --zoomCount; } break; case "hide": this.Hide(); break; case "show": this.Show(); break; } }); }
void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e) { string typeString = String.Empty; string notificationContent = String.Empty; switch (e.NotificationType) { case PushNotificationType.Badge: typeString = "Badge"; notificationContent = e.BadgeNotification.Content.GetXml(); break; case PushNotificationType.Tile: notificationContent = e.TileNotification.Content.GetXml(); typeString = "Tile"; break; case PushNotificationType.Toast: notificationContent = e.ToastNotification.Content.GetXml(); typeString = "Toast"; // Setting the cancel property prevents the notification from being delivered. It's especially important to do this for toasts: // if your application is already on the screen, there's no need to display a toast from push notifications. e.Cancel = true; break; case PushNotificationType.Raw: notificationContent = e.RawNotification.Content; typeString = "Raw"; break; } string text = "Received a " + typeString + " notification, containing: " + notificationContent; var ignored = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser(text, NotifyType.StatusMessage); }); }
private async Task StopRecording(CoreDispatcher dispatcher) { try { StorageFile localStorageFile = null; string path = string.Empty; if (capture != null) { await capture.StopRecordAsync(); IRandomAccessStream audio = buffer.CloneStream(); if (audio == null) { new ArgumentNullException("buffer"); } await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { localStorageFile = await storageFolder.CreateFileAsync(audioFilename, CreationCollisionOption.GenerateUniqueName); filename = localStorageFile.Name; path = localStorageFile.Path; using (IRandomAccessStream fileStream = await localStorageFile.OpenAsync(FileAccessMode.ReadWrite)) { await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0)); await audio.FlushAsync(); audio.Dispose(); } running = false; }); } } catch (Exception e) { throw e; } }
private async void Player_MediaEnded(object sender, Events.MediaEndedEventArgs e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { DontUpdatePosition = true; CurrentPosition = 0; player.PlayerState = PlayerState.Stopped; if (!Repeat) { await player.Pause(); timer.Stop(); PlayPauseIcon = new SymbolIcon(Symbol.Play); DontUpdatePosition = false; } else { timer.Start(); DontUpdatePosition = false; PlayPauseCommand.Execute(null); } }); }
public Task LoadCache(CoreDispatcher dispatcher, StorageFile cacheFile = null) { if (Interlocked.CompareExchange(ref _hasLoadedCache, 1, 0) == 1) { return(null); } return(Task.Run(new Action(() => { try { _cache = AsyncInline.Run(new Func <Task <MusicLibraryCache> >(() => MusicLibraryCache.Deserialize(cacheFile))); var c = dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { foreach (Artist artist in _cache.Artists.Values) { AddItemToGroup(ArtistGroupDictionary, artist, a => a.ArtistName[0]); } foreach (List <Album> albums in _cache.Albums.Values) { foreach (Album album in albums) { AddItemToGroup(AlbumGroupDictionary, album, a => a.AlbumName[0]); } } foreach (List <Song> songs in _cache.Songs.Values) { foreach (Song song in songs) { AddItemToGroup(SongGroupDictionary, song, a => song.SongTitle[0]); } } }); } catch { } }))); }
public IAsyncOperation <LoadMoreItemsResult> LoadMoreItemsAsync(uint count) { CoreDispatcher dispatcher = Window.Current != null ? Window.Current.Dispatcher : Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher; if (count > 50 || count <= 0) { // default load count to be set to 50 count = 50; } return(Task.Run <LoadMoreItemsResult>( async() => { IPagedResponse <K> result = await this.Source.GetPage(string.Format(this.Query, count), ++this.CurrentPage, (int)count); this.VirtualCount = result.VirtualCount; if (rpp == 0) { rpp = result.rpp; } await dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { foreach (K item in result.Items) { this.Add(item); } }); return new LoadMoreItemsResult() { Count = (uint)result.Items.Count() }; }).AsAsyncOperation <LoadMoreItemsResult>()); }