Skip to content

Commit

Permalink
Fixed dispatcher for Xaml Islands. leveraging DispatcherQueueHelper i…
Browse files Browse the repository at this point in the history
…n favor of DispatcherHelper.
  • Loading branch information
azchohfi committed Mar 31, 2020
1 parent 9c95639 commit 8464f8e
Show file tree
Hide file tree
Showing 25 changed files with 904 additions and 116 deletions.
2 changes: 1 addition & 1 deletion GazeInputTest/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.Toolkit.Uwp.Input.GazeInteraction;
using System;
using Microsoft.Toolkit.Uwp.Input.GazeInteraction;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
Expand Down
2 changes: 1 addition & 1 deletion GazeInputTest/MainPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.Toolkit.Uwp.Input.GazeInteraction;
using System;
using Microsoft.Toolkit.Uwp.Input.GazeInteraction;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Microsoft.Toolkit.Uwp.Helpers;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Enumeration;
using Windows.Foundation.Metadata;
using Windows.UI.Core;
using Windows.System;

namespace Microsoft.Toolkit.Uwp.Connectivity
{
Expand Down Expand Up @@ -59,11 +59,15 @@ public class BluetoothLEHelper
/// </summary>
private BluetoothAdapter _adapter;

private DispatcherQueue _dispatcherQueue;

/// <summary>
/// Prevents a default instance of the <see cref="BluetoothLEHelper" /> class from being created.
/// </summary>
private BluetoothLEHelper()
{
_dispatcherQueue = DispatcherQueue.GetForCurrentThread();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Init();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Expand Down Expand Up @@ -201,8 +205,7 @@ private async Task Init()
/// <param name="args">The advertisement.</param>
private async void AdvertisementWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
await _dispatcherQueue.ExecuteOnUIThreadAsync(
() =>
{
if (_readerWriterLockSlim.TryEnterReadLock(TimeSpan.FromSeconds(1)))
Expand All @@ -217,7 +220,7 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
_readerWriterLockSlim.ExitReadLock();
}
});
}, DispatcherQueuePriority.Normal);
}

/// <summary>
Expand Down Expand Up @@ -286,19 +289,20 @@ private async void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformation
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == _deviceWatcher)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (_readerWriterLockSlim.TryEnterWriteLock(TimeSpan.FromSeconds(1)))
await _dispatcherQueue.ExecuteOnUIThreadAsync(
() =>
{
var device = BluetoothLeDevices.FirstOrDefault(i => i.DeviceInfo.Id == deviceInfoUpdate.Id);
BluetoothLeDevices.Remove(device);
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);
var unusedDevice = _unusedDevices.FirstOrDefault(i => i.Id == deviceInfoUpdate.Id);
_unusedDevices?.Remove(unusedDevice);
_readerWriterLockSlim.ExitWriteLock();
}
});
_readerWriterLockSlim.ExitWriteLock();
}
}, DispatcherQueuePriority.Normal);
}
}

Expand Down Expand Up @@ -327,16 +331,15 @@ 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);
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 CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
await _dispatcherQueue.ExecuteOnUIThreadAsync(
() =>
{
if (_readerWriterLockSlim.TryEnterWriteLock(TimeSpan.FromSeconds(1)))
Expand All @@ -348,7 +351,7 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
_readerWriterLockSlim.ExitWriteLock();
}
});
}, DispatcherQueuePriority.Normal);

return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Microsoft.Toolkit.Uwp.Helpers;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml.Media.Imaging;

Expand Down Expand Up @@ -134,17 +135,22 @@ public int Compare(object x, object y)
private ObservableCollection<ObservableGattDeviceService> _services =
new ObservableCollection<ObservableGattDeviceService>();

private DispatcherQueue _dispatcherQueue;

/// <summary>
/// Initializes a new instance of the <see cref="ObservableBluetoothLEDevice"/> class.
/// </summary>
/// <param name="deviceInfo">The device information.</param>
public ObservableBluetoothLEDevice(DeviceInformation deviceInfo)
/// <param name="dispatcherQueue">The DispatcherQueue that should be used to dispatch UI updates for this BluetoothLE Device, or null if this is being called from the UI thread.</param>
public ObservableBluetoothLEDevice(DeviceInformation deviceInfo, DispatcherQueue dispatcherQueue = null)
{
DeviceInfo = deviceInfo;
Name = DeviceInfo.Name;

IsPaired = DeviceInfo.Pairing.IsPaired;

_dispatcherQueue = dispatcherQueue ?? DispatcherQueue.GetForCurrentThread();

LoadGlyph();

this.PropertyChanged += ObservableBluetoothLEDevice_PropertyChanged;
Expand Down Expand Up @@ -395,7 +401,8 @@ private void ObservableBluetoothLEDevice_PropertyChanged(object sender, Property
/// <exception cref="Exception">Thorws Exception when no permission to access device</exception>
public async Task ConnectAsync()
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
await _dispatcherQueue.ExecuteOnUIThreadAsync(
async () =>
{
if (BluetoothLEDevice == null)
{
Expand Down Expand Up @@ -442,7 +449,7 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPrio
throw new Exception(_result.ProtocolError.GetErrorString());
}
}
});
}, DispatcherQueuePriority.Normal);
}

/// <summary>
Expand All @@ -468,8 +475,7 @@ public async Task DoInAppPairingAsync()
/// <returns>The task of the update.</returns>
public async Task UpdateAsync(DeviceInformationUpdate deviceUpdate)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
await _dispatcherQueue.ExecuteOnUIThreadAsync(
() =>
{
DeviceInfo.Update(deviceUpdate);
Expand All @@ -479,7 +485,7 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
LoadGlyph();
OnPropertyChanged("DeviceInfo");
});
}, DispatcherQueuePriority.Normal);
}

/// <summary>
Expand Down Expand Up @@ -512,9 +518,7 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName
/// <param name="args">The arguments.</param>
private async void BluetoothLEDevice_NameChanged(BluetoothLEDevice sender, object args)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() => { Name = BluetoothLEDevice.Name; });
await _dispatcherQueue.ExecuteOnUIThreadAsync(() => { Name = BluetoothLEDevice.Name; }, DispatcherQueuePriority.Normal);
}

/// <summary>
Expand All @@ -524,29 +528,27 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
/// <param name="args">The arguments.</param>
private async void BluetoothLEDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
await _dispatcherQueue.ExecuteOnUIThreadAsync(
() =>
{
IsPaired = DeviceInfo.Pairing.IsPaired;
IsConnected = BluetoothLEDevice.ConnectionStatus == BluetoothConnectionStatus.Connected;
});
}, DispatcherQueuePriority.Normal);
}

/// <summary>
/// Load the glyph for this device
/// </summary>
private async void LoadGlyph()
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
await _dispatcherQueue.ExecuteOnUIThreadAsync(
async () =>
{
var deviceThumbnail = await DeviceInfo.GetGlyphThumbnailAsync();
var glyphBitmapImage = new BitmapImage();
await glyphBitmapImage.SetSourceAsync(deviceThumbnail);
Glyph = glyphBitmapImage;
});
}, DispatcherQueuePriority.Normal);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.Toolkit.Uwp.Helpers;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Security.Cryptography;
using Windows.Storage.Streams;
using Windows.System;

namespace Microsoft.Toolkit.Uwp.Connectivity
{
Expand Down Expand Up @@ -110,13 +112,17 @@ public enum DisplayTypes
/// </summary>
private string _value;

private DispatcherQueue _dispatcherQueue;

/// <summary>
/// Initializes a new instance of the <see cref="ObservableGattCharacteristics"/> class.
/// </summary>
/// <param name="characteristic">The characteristic.</param>
/// <param name="parent">The parent.</param>
public ObservableGattCharacteristics(GattCharacteristic characteristic, ObservableGattDeviceService parent)
{
_dispatcherQueue = DispatcherQueue.GetForCurrentThread();

Characteristic = characteristic;
Parent = parent;
Name = GattUuidsService.ConvertUuidToName(Characteristic.Uuid);
Expand Down Expand Up @@ -459,9 +465,7 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName
/// <param name="args">The <see cref="GattValueChangedEventArgs"/> instance containing the event data.</param>
private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
() => { SetValue(args.CharacteristicValue); });
await _dispatcherQueue.ExecuteOnUIThreadAsync(() => { SetValue(args.CharacteristicValue); }, DispatcherQueuePriority.Normal);
}

/// <summary>
Expand Down
12 changes: 8 additions & 4 deletions Microsoft.Toolkit.Uwp.SampleApp/Controls/CodeRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,14 @@ protected override void OnApplyTemplate()

private void RenderDocument()
{
_codeView?.Blocks?.Clear();
_formatter = new RichTextBlockFormatter(_theme);
_formatter.FormatRichTextBlock(_displayedText, _language, _codeView);
_rendered = true;
if (_codeView != null)
{
_codeView.Blocks?.Clear();
_formatter = new RichTextBlockFormatter(_theme);

_formatter.FormatRichTextBlock(_displayedText, _language, _codeView);
_rendered = true;
}
}

private void CopyButton_Click(object sender, RoutedEventArgs e)
Expand Down
3 changes: 2 additions & 1 deletion Microsoft.Toolkit.Uwp.SampleApp/Shell.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.Toolkit.Uwp.Helpers;
using Microsoft.Toolkit.Uwp.SampleApp.Pages;
using Microsoft.Toolkit.Uwp.UI.Extensions;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
Expand Down Expand Up @@ -127,7 +128,7 @@ private void SamplePickerGridView_Loaded(object sender, Windows.UI.Xaml.RoutedEv
{
if (s is UIElement samplePicker && samplePicker.Visibility == Visibility.Visible)
{
DispatcherHelper.ExecuteOnUIThreadAsync(() => SamplePickerGridView.Focus(FocusState.Keyboard));
DispatcherQueue.GetForCurrentThread().ExecuteOnUIThreadAsync(() => SamplePickerGridView.Focus(FocusState.Keyboard));
}
});
}
Expand Down
6 changes: 5 additions & 1 deletion Microsoft.Toolkit.Uwp.UI/Cache/ImageCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Microsoft.Toolkit.Uwp.Helpers;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.System;
using Windows.UI.Xaml.Media.Imaging;

namespace Microsoft.Toolkit.Uwp.UI
Expand All @@ -34,11 +35,14 @@ public class ImageCache : CacheBase<BitmapImage>
/// </summary>
public static ImageCache Instance => _instance ?? (_instance = new ImageCache());

private DispatcherQueue _dispatcherQueue;

/// <summary>
/// Initializes a new instance of the <see cref="ImageCache"/> class.
/// </summary>
public ImageCache()
{
_dispatcherQueue = DispatcherQueue.GetForCurrentThread();
_extendedPropertyNames.Add(DateAccessedProperty);
}

Expand All @@ -55,7 +59,7 @@ protected override async Task<BitmapImage> InitializeTypeAsync(Stream stream, Li
throw new FileNotFoundException();
}

return await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
return await _dispatcherQueue.ExecuteOnUIThreadAsync(async () =>
{
BitmapImage image = new BitmapImage();
Expand Down
Loading

0 comments on commit 8464f8e

Please sign in to comment.