/// <summary> /// Updates the search box items source when the user changes the search text. /// </summary> private async void CustomerSearchBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { // We only want to get results when it was a user typing, // otherwise we assume the value got filled in by TextMemberPath // or the handler for SuggestionChosen. if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput) { // If no search query is entered, refresh the complete list. if (String.IsNullOrEmpty(sender.Text)) { await dispatcherQueue.EnqueueAsync(async() => await ViewModel.GetCustomerListAsync()); sender.ItemsSource = null; } else { string[] parameters = sender.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); sender.ItemsSource = ViewModel.Customers .Where(customer => parameters.Any(parameter => customer.Address.StartsWith(parameter, StringComparison.OrdinalIgnoreCase) || customer.FirstName.StartsWith(parameter, StringComparison.OrdinalIgnoreCase) || customer.LastName.StartsWith(parameter, StringComparison.OrdinalIgnoreCase) || customer.Company.StartsWith(parameter, StringComparison.OrdinalIgnoreCase))) .OrderByDescending(customer => parameters.Count(parameter => customer.Address.StartsWith(parameter) || customer.FirstName.StartsWith(parameter) || customer.LastName.StartsWith(parameter) || customer.Company.StartsWith(parameter))) .Select(customer => $"{customer.FirstName} {customer.LastName}"); } } }
public async ValueTask ClearAsync() { await _dispatcherQueue.EnqueueAsync(() => { base.Clear(); StopPlaybackMedia(); ClearPlaylist(); }); }
private async Task <bool> OpenPage(string pageName) { try { Log.Comment("Trying to Load Page: " + pageName); _loadingStateTask = new TaskCompletionSource <bool>(); // Ensure we're on the UI thread as we'll be called from the AppService now. _ = _queue.EnqueueAsync(() => { // Navigate without extra animations navigationFrame.Navigate(FindPageType(pageName), new SuppressNavigationTransitionInfo()); }); // Wait for load to complete await _loadingStateTask.Task; } catch (Exception e) { Log.Error("Exception Loading Page {0}: {1} ", pageName, e.Message); return(false); } return(true); }
private async Task RefreshQrAsync() { var data = await App.Repository.Authorize.QrRefreshAsync(); if (data == null) { return; } await dispatcherQueue.EnqueueAsync(() => { Token = data.Token; QrImage.Source = Converters.ConverterHelper.ToImg(data.Qr); changeStatus(QrStatus.NONE); loopCheckQr(); }); }
/// <summary> /// Calls an Event registered before with the <see cref="RegisterEvent(string, Func{string[], Task{string}})"/>. /// </summary> /// <param name="name">Name of event to call.</param> /// <param name="parameters">JSON string Parameters.</param> /// <returns></returns> public IAsyncOperation <string> CallEvent(string name, [ReadOnlyArray] string[] parameters) { return(AsyncInfo.Run(async delegate(CancellationToken token) { string result = null; await _queue.EnqueueAsync(async() => { if (events.ContainsKey(name)) { result = await events[name]?.Invoke(parameters); } }); return result; })); }
/// <summary> /// Executes when the connection state changes /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The arguments.</param> private async void BluetoothLEDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args) { await DispatcherQueue.EnqueueAsync( () => { IsPaired = DeviceInfo.Pairing.IsPaired; IsConnected = BluetoothLEDevice.ConnectionStatus == BluetoothConnectionStatus.Connected; }, DispatcherQueuePriority.Normal); }
/// <summary> /// Loads the customer with the specified ID. /// </summary> private async void LoadCustomer(Guid customerId) { var customer = await App.Repository.Customers.GetAsync(customerId); await dispatcherQueue.EnqueueAsync(() => { Customer = customer; }); }
/// <summary> /// Creates and adds one print preview page to the internal cache of print preview pages stored in <see cref="_printPreviewPages"/>. /// </summary> /// <param name="element">FrameworkElement used to represent the "printing page"</param> /// <param name="printPageDescription">Printer's page description</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> private Task AddOnePrintPreviewPage(FrameworkElement element, PrintPageDescription printPageDescription) { var page = new Page(); // Save state if (!_stateBags.ContainsKey(element)) { var stateBag = new PrintHelperStateBag(); stateBag.Capture(element); _stateBags.Add(element, stateBag); } // Set "paper" width page.Width = printPageDescription.PageSize.Width; page.Height = printPageDescription.PageSize.Height; // Get the margins size double marginWidth = Math.Max(printPageDescription.PageSize.Width - printPageDescription.ImageableRect.Width, printPageDescription.PageSize.Width * ApplicationContentMarginLeft * 2); double marginHeight = Math.Max(printPageDescription.PageSize.Height - printPageDescription.ImageableRect.Height, printPageDescription.PageSize.Height * ApplicationContentMarginTop * 2); // Set up the "printable area" on the "paper" element.VerticalAlignment = VerticalAlignment.Top; element.HorizontalAlignment = HorizontalAlignment.Left; if (element.Width > element.Height) { var newWidth = page.Width - marginWidth; element.Height = element.Height * (newWidth / element.Width); element.Width = newWidth; } else { var newHeight = page.Height - marginHeight; element.Width = element.Width * (newHeight / element.Height); element.Height = newHeight; } element.Margin = new Thickness(marginWidth / 2, marginHeight / 2, marginWidth / 2, marginHeight / 2); page.Content = element; return(DispatcherQueue.EnqueueAsync( () => { // Add the (newly created) page to the print canvas which is part of the visual tree and force it to go // through layout so that the linked containers correctly distribute the content inside them. _printCanvas.Children.Add(page); _printCanvas.UpdateLayout(); _printCanvas.InvalidateMeasure(); // Add the page to the page preview collection _printPreviewPages.Add(page); }, DispatcherQueuePriority.High)); }
/// <summary> /// Load the glyph for this device /// </summary> private async void LoadGlyph() { await DispatcherQueue.EnqueueAsync( async() => { var deviceThumbnail = await DeviceInfo.GetGlyphThumbnailAsync(); var glyphBitmapImage = new BitmapImage(); await glyphBitmapImage.SetSourceAsync(deviceThumbnail); Glyph = glyphBitmapImage; }, DispatcherQueuePriority.Normal); }
/// <summary> /// Restores stored state to given element. /// </summary> /// <param name="element">Element to restore state to</param> public void Restore(FrameworkElement element) { _dispatcherQueue.EnqueueAsync(() => { element.HorizontalAlignment = HorizontalAlignment; element.VerticalAlignment = VerticalAlignment; element.Width = Width; element.Height = Height; element.Margin = Margin; }); }
private static void SetCursorType(DispatcherQueue dispatcherQueue, double offsetX, double offsetY) { if (!_isCursorAvailable) { return; } uint cursorID = 101; if (Math.Abs(offsetX) < _threshold && Math.Abs(offsetY) < _threshold) { cursorID = 101; } else if (Math.Abs(offsetX) < _threshold && offsetY < -_threshold) { cursorID = 102; } else if (offsetX > _threshold && offsetY < -_threshold) { cursorID = 103; } else if (offsetX > _threshold && Math.Abs(offsetY) < _threshold) { cursorID = 104; } else if (offsetX > _threshold && offsetY > _threshold) { cursorID = 105; } else if (Math.Abs(offsetX) < _threshold && offsetY > _threshold) { cursorID = 106; } else if (offsetX < -_threshold && offsetY > _threshold) { cursorID = 107; } else if (offsetX < -_threshold && Math.Abs(offsetY) < _threshold) { cursorID = 108; } else if (offsetX < -_threshold && offsetY < -_threshold) { cursorID = 109; } if (_oldCursorID != cursorID) { dispatcherQueue.EnqueueAsync(() => Window.Current.CoreWindow.PointerCursor = new CoreCursor(CoreCursorType.Custom, cursorID)); _oldCursorID = cursorID; } }
/// <summary> /// ConnectAsync to this bluetooth device /// </summary> /// <returns>Connection task</returns> /// <exception cref="Exception">Throws Exception when no permission to access device</exception> public async Task ConnectAsync() { await DispatcherQueue.EnqueueAsync( async() => { if (BluetoothLEDevice == null) { BluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(DeviceInfo.Id); if (BluetoothLEDevice == null) { throw new Exception("Connection error, no permission to access device"); } } BluetoothLEDevice.ConnectionStatusChanged += BluetoothLEDevice_ConnectionStatusChanged; BluetoothLEDevice.NameChanged += BluetoothLEDevice_NameChanged; IsPaired = DeviceInfo.Pairing.IsPaired; IsConnected = BluetoothLEDevice.ConnectionStatus == BluetoothConnectionStatus.Connected; Name = BluetoothLEDevice.Name; // Get all the services for this device var getGattServicesAsyncTokenSource = new CancellationTokenSource(5000); var getGattServicesAsyncTask = await Task.Run( () => BluetoothLEDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached), getGattServicesAsyncTokenSource.Token); _result = await getGattServicesAsyncTask; if (_result.Status == GattCommunicationStatus.Success) { // In case we connected before, clear the service list and recreate it Services.Clear(); foreach (var service in _result.Services) { Services.Add(new ObservableGattDeviceService(service)); } ServiceCount = Services.Count; } else { if (_result.ProtocolError != null) { throw new Exception(_result.ProtocolError.GetErrorString()); } } }, DispatcherQueuePriority.Normal); }
/// <summary> /// Updates this device's deviceInformation /// </summary> /// <param name="deviceUpdate">The device information which has been updated.</param> /// <returns>The task of the update.</returns> public async Task UpdateAsync(DeviceInformationUpdate deviceUpdate) { await DispatcherQueue.EnqueueAsync( () => { DeviceInfo.Update(deviceUpdate); Name = DeviceInfo.Name; IsPaired = DeviceInfo.Pairing.IsPaired; LoadGlyph(); OnPropertyChanged("DeviceInfo"); }, DispatcherQueuePriority.Normal); }
/// <summary> /// Restores stored state to given element. /// </summary> /// <param name="element">Element to restore state to</param> public void Restore(FrameworkElement element) { DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread(); dispatcherQueue.EnqueueAsync(() => //DispatcherHelper.ExecuteOnUIThreadAsync(() => { element.HorizontalAlignment = HorizontalAlignment; element.VerticalAlignment = VerticalAlignment; element.Width = Width; element.Height = Height; element.Margin = Margin; }); }
private Task ClearPageCache() { return(DispatcherQueue.EnqueueAsync(() => { if (!_directPrint) { foreach (Page page in _printPreviewPages) { page.Content = null; } } _printPreviewPages.Clear(); })); }
// Note: This can get called multiple times during HighContrast switch, do we care? private async void _settings_ColorValuesChanged(UISettings sender, object args) { // Getting called off thread, so we need to dispatch to request value. await _queue.EnqueueAsync(() => { // TODO: This doesn't stop the multiple calls if we're in our faked 'White' HighContrast Mode below. if (CurrentTheme != Application.Current.RequestedTheme || IsHighContrast != _accessible.HighContrast) { #if DEBUG Debug.WriteLine("Color Values Changed"); #endif UpdateProperties(); } }); }
/// <summary> /// Release associated resources /// </summary> public void Dispose() { if (_printDocument == null) { return; } _printCanvas = null; DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread(); dispatcherQueue.EnqueueAsync(() => //DispatcherHelper.ExecuteOnUIThreadAsync(() => { _printDocument.Paginate -= CreatePrintPreviewPages; _printDocument.GetPreviewPage -= GetPrintPreviewPage; _printDocument.AddPages -= AddPrintPages; }); }
private Task ClearPageCache() { DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread(); return(dispatcherQueue.EnqueueAsync(() => //return DispatcherHelper.ExecuteOnUIThreadAsync(() => { if (!_directPrint) { foreach (Page page in _printPreviewPages) { page.Content = null; } } _printPreviewPages.Clear(); })); }
/// <summary> /// 解析二维码图片 /// </summary> /// <param name="writeableBmp">图片</param> /// <returns></returns> private async Task ScanBitmapAsync(SoftwareBitmap bitmap) { try { await dispatcherQueue.EnqueueAsync(() => { var result = barcodeReader.Decode(bitmap); if (result != null) { Frame.Navigate(typeof(AuthorizePage), result.Text); } }); } catch (Exception ex) { Log.Info(ex); return; } }
/// <summary> /// Updates device metadata based on advertisement received /// </summary> /// <param name="sender">The Bluetooth LE Advertisement Watcher.</param> /// <param name="args">The advertisement.</param> private async void AdvertisementWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { await DispatcherQueue.EnqueueAsync( () => { if (_readerWriterLockSlim.TryEnterReadLock(TimeSpan.FromSeconds(1))) { foreach (var device in BluetoothLeDevices) { if (device.BluetoothAddressAsUlong == args.BluetoothAddress) { device.ServiceCount = args.Advertisement.ServiceUuids.Count(); } } _readerWriterLockSlim.ExitReadLock(); } }, DispatcherQueuePriority.Normal); }
/// <summary> /// Executes when a device is removed from enumeration /// </summary> /// <param name="sender">The device watcher.</param> /// <param name="deviceInfoUpdate">An update of the device.</param> private async void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) { // Protect against race condition if the task runs after the app stopped the deviceWatcher. if (sender == _deviceWatcher) { await DispatcherQueue.EnqueueAsync( () => { if (_readerWriterLockSlim.TryEnterWriteLock(TimeSpan.FromSeconds(1))) { var device = BluetoothLeDevices.FirstOrDefault(i => i.DeviceInfo.Id == deviceInfoUpdate.Id); BluetoothLeDevices.Remove(device); var unusedDevice = _unusedDevices.FirstOrDefault(i => i.Id == deviceInfoUpdate.Id); _unusedDevices?.Remove(unusedDevice); _readerWriterLockSlim.ExitWriteLock(); } }, DispatcherQueuePriority.Normal); } }
private async Task LoadDataAsync() { if (Source != null) { return; } Source = await App.Repository.Site.GetEmojiAsync(); if (Source == null) { return; } await dispatcherQueue.EnqueueAsync(() => { CatBox.Items.Clear(); foreach (var item in Source) { CatBox.Items.Add(item.Name); } SelectedCategory(0); }); }
///// <summary> ///// Method that will generate print content for the scenario ///// For scenarios 1-4: it will create the first page from which content will flow ///// Scenario 5 uses a different approach ///// </summary> ///// <param name="page">The page to print</param> //public void PreparePrintContent(Page page) //{ // if (_firstPage == null) // { // _firstPage = page; // //StackPanel header = (StackPanel)firstPage.FindName("Header"); // //header.Visibility = Windows.UI.Xaml.Visibility.Visible; // } // // Add the (newly created) page to the print canvas which is part of the visual tree and force it to go // // through layout so that the linked containers correctly distribute the content inside them. // _printCanvas.Children.Add(_firstPage); // _printCanvas.InvalidateMeasure(); // _printCanvas.UpdateLayout(); //} private async Task DetachCanvas() { if (!_directPrint) { DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread(); await dispatcherQueue.EnqueueAsync(() => //await DispatcherHelper.ExecuteOnUIThreadAsync(() => { _canvasContainer.Children.Remove(_printCanvas); _printCanvas.Children.Clear(); }); } _stateBags.Clear(); // Clear the cache of preview pages await ClearPageCache(); // Remove the handler for printing initialization. PrintManager printMan = PrintManager.GetForCurrentView(); printMan.PrintTaskRequested -= PrintTaskRequested; }
/// <summary> /// Adds the new or updated device to the displayed or unused list /// </summary> /// <param name="deviceInfo">The device to add</param> /// <returns>The task being used to add a device to a list</returns> private async Task AddDeviceToList(DeviceInformation deviceInfo) { // Make sure device name isn't blank or already present in the list. if (!string.IsNullOrEmpty(deviceInfo?.Name)) { var device = new ObservableBluetoothLEDevice(deviceInfo, DispatcherQueue); var connectable = (device.DeviceInfo.Properties.Keys.Contains("System.Devices.Aep.Bluetooth.Le.IsConnectable") && (bool)device.DeviceInfo.Properties["System.Devices.Aep.Bluetooth.Le.IsConnectable"]) || (device.DeviceInfo.Properties.Keys.Contains("System.Devices.Aep.IsConnected") && (bool)device.DeviceInfo.Properties["System.Devices.Aep.IsConnected"]); if (connectable) { await DispatcherQueue.EnqueueAsync( () => { if (_readerWriterLockSlim.TryEnterWriteLock(TimeSpan.FromSeconds(1))) { if (!BluetoothLeDevices.Contains(device)) { BluetoothLeDevices.Add(device); } _readerWriterLockSlim.ExitWriteLock(); } }, DispatcherQueuePriority.Normal); return; } } if (_readerWriterLockSlim.TryEnterWriteLock(TimeSpan.FromSeconds(1))) { _unusedDevices.Add(deviceInfo); _readerWriterLockSlim.ExitWriteLock(); } }
public Task RunAsync(Action action, int priority) => Dispatcher.EnqueueAsync(action, (DispatcherQueuePriority)priority);
private static async void RunInUIThread(DispatcherQueue dispatcherQueue, Action action) { await dispatcherQueue.EnqueueAsync(action, DispatcherQueuePriority.Normal); }
/// <summary> /// Executes when the name of this devices changes /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The arguments.</param> private async void BluetoothLEDevice_NameChanged(BluetoothLEDevice sender, object args) { await DispatcherQueue.EnqueueAsync(() => { Name = BluetoothLEDevice.Name; }, DispatcherQueuePriority.Normal); }
public Task ExecuteOnUiThreadAsync(Action action) { return(_dispatcherQueue.EnqueueAsync(action)); }
public void RenderDiff(string left, string right, ElementTheme theme) { StopRenderingAndClearCache(); var foregroundBrush = (theme == ElementTheme.Dark) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Colors.Black); var diffContext = _diffRenderer.GenerateDiffViewData(left, right, foregroundBrush); var leftContext = diffContext.Item1; var rightContext = diffContext.Item2; var leftHighlighters = leftContext.GetTextHighlighters(); var rightHighlighters = rightContext.GetTextHighlighters(); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); Task.Factory.StartNew(async() => { var leftCount = leftContext.Blocks.Count; var rightCount = rightContext.Blocks.Count; var leftStartIndex = 0; var rightStartIndex = 0; var threshold = 1; while (true) { Thread.Sleep(10); if (leftStartIndex < leftCount) { var end = leftStartIndex + threshold; if (end >= leftCount) { end = leftCount; } var start = leftStartIndex; await DispatcherQueue.EnqueueAsync(() => { for (int x = start; x < end; x++) { if (cancellationTokenSource.IsCancellationRequested) { return; } LeftTextBlock.Blocks.Add(leftContext.Blocks[x]); } }, Microsoft.UI.Dispatching.DispatcherQueuePriority.High); } if (rightStartIndex < rightCount) { var end = rightStartIndex + threshold; if (end >= rightCount) { end = rightCount; } var start = rightStartIndex; await DispatcherQueue.EnqueueAsync(() => { for (int x = start; x < end; x++) { if (cancellationTokenSource.IsCancellationRequested) { return; } RightTextBlock.Blocks.Add(rightContext.Blocks[x]); } }, Microsoft.UI.Dispatching.DispatcherQueuePriority.High); } leftStartIndex += threshold; rightStartIndex += threshold; threshold *= 5; if (leftStartIndex >= leftCount && rightStartIndex >= rightCount) { break; } } }, cancellationTokenSource.Token); Task.Factory.StartNew(async() => { var leftCount = leftHighlighters.Count; var rightCount = rightHighlighters.Count; var leftStartIndex = 0; var rightStartIndex = 0; var threshold = 5; while (true) { Thread.Sleep(10); if (leftStartIndex < leftCount) { var end = leftStartIndex + threshold; if (end >= leftCount) { end = leftCount; } var start = leftStartIndex; await DispatcherQueue.EnqueueAsync(() => { for (int x = start; x < end; x++) { if (cancellationTokenSource.IsCancellationRequested) { return; } LeftTextBlock.TextHighlighters.Add(leftHighlighters[x]); } }, Microsoft.UI.Dispatching.DispatcherQueuePriority.High); } if (rightStartIndex < rightCount) { var end = rightStartIndex + threshold; if (end >= rightCount) { end = rightCount; } var start = rightStartIndex; await DispatcherQueue.EnqueueAsync(() => { for (int x = start; x < end; x++) { if (cancellationTokenSource.IsCancellationRequested) { return; } RightTextBlock.TextHighlighters.Add(rightHighlighters[x]); } }, Microsoft.UI.Dispatching.DispatcherQueuePriority.High); } leftStartIndex += threshold; rightStartIndex += threshold; threshold *= 5; if (leftStartIndex >= leftCount && rightStartIndex >= rightCount) { break; } } }, cancellationTokenSource.Token); _cancellationTokenSource = cancellationTokenSource; }
/// <summary> /// When the Characteristics value changes. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="GattValueChangedEventArgs"/> instance containing the event data.</param> private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { await DispatcherQueue.EnqueueAsync(() => { SetValue(args.CharacteristicValue); }, DispatcherQueuePriority.Normal); }