Why is CreateFileAsync() continuation not executed? - windows-runtime

In the below code, the continuation of CreateFileAsync() neither prints nor accesses pdone. However, the zero-length file, Hello.txt, is created.
auto pdone = make_shared<bool>(false);
create_task(folderLocal->CreateFileAsync("Hello.txt", CreationCollisionOption::ReplaceExisting)).then([pdone](StorageFile ^file) {
OutputDebugString(L"In CreateFileAsync continuation!\n");
*pdone = true;
});
create_task([pdone]{
OutputDebugString(L"In my task!\n");
});
create_async([pdone]{
OutputDebugString(L"In my async!\n");
});
while (!*pdone) {}
OutputDebugString(L"Done!\n");
In the debugger:
In my task!
In my async!
I'm not very familiar with debugging WinRT threads yet, but I do not see any obvious exception or any reason the continuation to the async operation should not execute. The target platform is the Hololens emulator.
Any thoughts are appreciated.
Thanks!

Harry's comment above is most likely the culprit - if you initiated this on a UI thread then by default the C++ tasks library (PPL) will try to schedule the completion on the same thread. This will never happen if you are spinning the thread waiting for the completion to happen (classic deadlock).
If you must do this (although you really should try and avoid it) you need to use a "continuation context" to tell PPL to run the continuation somewhere else.
Here's an example. First, basic XAML (just paste inside the Grid of a blank C++ XAML project):
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Content="Hang the UI thread" Click="Hang"/>
<Button Content="Do not do this" Click="DoNotDoThis"/>
</StackPanel>
And the code (just paste after the MainPage constructor):
using namespace Windows::Storage;
using namespace concurrency;
void DoIt(task_continuation_context& context)
{
auto folder = ApplicationData::Current->LocalFolder;
auto done = std::make_shared<bool>(false);
create_task(folder->CreateFileAsync(L"x", CreationCollisionOption::ReplaceExisting))
.then([done](StorageFile^ file) mutable
{
OutputDebugString(L"Done creating file\n");
*done = true;
}, context);
OutputDebugString(L"Going to wait... DO NOT DO THIS IN PRODUCTION CODE!\n");
while (!*done)
;
OutputDebugString(L"Done waiting\n");
}
void MainPage::Hang(Platform::Object^ sender, RoutedEventArgs^ e)
{
OutputDebugString(L"Starting Hang\n");
// The default context == the UI thread (if called from UI)
DoIt(task_continuation_context::use_default());
OutputDebugString(L"Ending Hang\n");
}
void MainPage::DoNotDoThis(Platform::Object^ sender, RoutedEventArgs^ e)
{
OutputDebugString(L"Starting DoNotDoThis\n");
// An arbitrary context will pick another thread (not the UI)
DoIt(task_continuation_context::use_arbitrary());
OutputDebugString(L"Ending DoNotDoThis\n");
}
As noted, you shouldn't do this. If you need synchronous File I/O, and you're accessing files in your own package, use the Win32 API CreateFile2. If you need to access files outside of your package (eg, from a file picker or the photos library) you should use a fully-async programming approach.

I believe using task_continuation_context::use_arbitarty() is the correct way of doing this, however I think microsoft suggests using it slightly differently unless i have misunderstood this link (scroll all the way to the bottom): https://msdn.microsoft.com/en-us/library/hh750082.aspx
create_task(folderLocal->CreateFileAsync("Hello.txt", CreationCollisionOption::ReplaceExisting)).then([pdone](StorageFile ^file) {
OutputDebugString(L"In CreateFileAsync continuation!\n");
*pdone = true;
}, task_continuation_context::use_arbitrary());

Related

Enforce Microsoft.Build to reload the project

I'm trying to iteratively (part of automation):
Create backup of the projects in solution (physical files on the filesystem)
Using Microsoft.Build programmatically load and change projects inside of the solution (refernces, includes, some other properties)
Build it with console call of msbuild
Restore projects (physically overriding patched versions from backups)
This approach works well for first iteration, but for second it appears that it does not load restored projects and trying to work with values that I patched on the first iteration. It looks like projects are cached: inside of the csproj files I see correct values, but on the code I see previously patched values.
My best guess is that Microsoft.Build is caching solution/projects in the context of the current process.
Here is code that is responsible to load project and call method to update project information:
private static void ForEachProject(string slnPath, Func<ProjectRootElement> patchProject)
{
SolutionFile slnFile = SolutionFile.Parse(slnPath);
var filtredProjects = slnFile
.ProjectsInOrder
.Where(prj => prj.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat);
foreach (ProjectInSolution projectInfo in filtredProjects)
{
try
{
ProjectRootElement project = ProjectRootElement.Open(projectInfo.AbsolutePath);
patchProject(project);
project.Save();
}
catch (InvalidProjectFileException ex)
{
Console.WriteLine("Failed to patch project '{0}' with error: {1}", projectInfo.AbsolutePath, ex);
}
}
}
There is Reload method for the ProjectRootElement that migh be called before iteraction with content of the project.
It will enforce Microsoft.Build to read latest information from the file.
Code that is working for me:
private static void ForEachProject(string slnPath, Func<ProjectRootElement> patchProject)
{
SolutionFile slnFile = SolutionFile.Parse(slnPath);
var filtredProjects = slnFile
.ProjectsInOrder
.Where(prj => prj.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat);
foreach (ProjectInSolution projectInfo in filtredProjects)
{
try
{
ProjectRootElement project = ProjectRootElement.Open(projectInfo.AbsolutePath);
project.Reload(false); // Ignore cached state, read actual from the file
patchProject(project);
project.Save();
}
catch (InvalidProjectFileException ex)
{
Console.WriteLine("Failed to patch project '{0}' with error: {1}", projectInfo.AbsolutePath, ex);
}
}
}
Note: It better to use custom properties inside of the project and provide it for each msbuild call instead of physical project patching. Please consider it as better solution and use it if possible.

Trying to get C++/WinRT non UWP program to recognize bluetooth LE devices: specific failure at get_weak() (error:not defined)

I'm taking a shot at using C++/WinRT to find and communicate with Bluetooth LE devices in a non-UWP app.
(I'm trying to avoid UWP, as there appear to be some constraints on what you can do with it, and it looks kind of bloated to me.)
My background is a lot of programming and releasing for small-group distribution old-fashioned C++ WinMain-based programming, as in Petzold's "Programming Windows 95". My experience has been using the Win32 API only.
Unfortunately for me, MS documentation indicates that Bluetooth LE is not supported in Win32, and only in WinRT. Thus, this forces me to use something like C++/WinRT to access the API.
So, I took a shot at it by downloading the only available example of bluetooth LE access in C++ which I know of at all, which is Microsoft's C++WinRT UWP example.
I got that running as one Visual Studio 2022 project, and, since I am looking for a non-UWP program, I tried putting the relevant stuff into another project, for which I used Microsoft VS2022's built-in template for a C++/WinRT Console. When I try to stick into that what appearVS says to be the key elements of the C++/WinRT UWP example, and make modifications to fix obvious problems, I have an error in the code which I have no idea how to fix: it is on the several get_weak() calls, which VS intellisense says are "undefined". (The compile also fails with unable to find main.g.h and main.g.cpp .
Here is the code:
File main.h:
#pragma once
#include "main.g.h"
class find_devs
{
find_devs() {};
private:
std::vector<Windows::Devices::Enumeration::DeviceInformation> UnknownDevices;
Windows::Devices::Enumeration::DeviceWatcher deviceWatcher{ nullptr };
event_token deviceWatcherAddedToken;
event_token deviceWatcherUpdatedToken;
event_token deviceWatcherRemovedToken;
event_token deviceWatcherEnumerationCompletedToken;
event_token deviceWatcherStoppedToken;
void StartBleDeviceWatcher();
void StopBleDeviceWatcher();
std::vector<Windows::Devices::Enumeration::DeviceInformation>::iterator FindUnknownDevices(hstring const& id);
fire_and_forget DeviceWatcher_Added(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformation deviceInfo);
fire_and_forget DeviceWatcher_Updated(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate);
fire_and_forget DeviceWatcher_Removed(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate);
fire_and_forget DeviceWatcher_EnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Foundation::IInspectable const&);
fire_and_forget DeviceWatcher_Stopped(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Foundation::IInspectable const&);
};
and main.cpp:
#include "pch.h"
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Devices::Enumeration;
#include "pch.h"
#include "main.h"
#include "main.g.cpp"
using namespace winrt;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Foundation;
namespace winrt
{
hstring to_hstring(DevicePairingResultStatus status)
{
switch (status)
{
case DevicePairingResultStatus::Paired: return L"Paired";
case DevicePairingResultStatus::NotReadyToPair: return L"NotReadyToPair";
case DevicePairingResultStatus::NotPaired: return L"NotPaired";
case DevicePairingResultStatus::AlreadyPaired: return L"AlreadyPaired";
case DevicePairingResultStatus::ConnectionRejected: return L"ConnectionRejected";
case DevicePairingResultStatus::TooManyConnections: return L"TooManyConnections";
case DevicePairingResultStatus::HardwareFailure: return L"HardwareFailure";
case DevicePairingResultStatus::AuthenticationTimeout: return L"AuthenticationTimeout";
case DevicePairingResultStatus::AuthenticationNotAllowed: return L"AuthenticationNotAllowed";
case DevicePairingResultStatus::AuthenticationFailure: return L"AuthenticationFailure";
case DevicePairingResultStatus::NoSupportedProfiles: return L"NoSupportedProfiles";
case DevicePairingResultStatus::ProtectionLevelCouldNotBeMet: return L"ProtectionLevelCouldNotBeMet";
case DevicePairingResultStatus::AccessDenied: return L"AccessDenied";
case DevicePairingResultStatus::InvalidCeremonyData: return L"InvalidCeremonyData";
case DevicePairingResultStatus::PairingCanceled: return L"PairingCanceled";
case DevicePairingResultStatus::OperationAlreadyInProgress: return L"OperationAlreadyInProgress";
case DevicePairingResultStatus::RequiredHandlerNotRegistered: return L"RequiredHandlerNotRegistered";
case DevicePairingResultStatus::RejectedByHandler: return L"RejectedByHandler";
case DevicePairingResultStatus::RemoteDeviceHasAssociation: return L"RemoteDeviceHasAssociation";
case DevicePairingResultStatus::Failed: return L"Failed";
}
return L"Code " + to_hstring(static_cast<int>(status));
}
}
// This scenario uses a DeviceWatcher to enumerate nearby Bluetooth Low Energy devices,
// displays them in a ListView, and lets the user select a device and pair it.
// This device will be used by future scenarios.
// For more information about device discovery and pairing, including examples of
// customizing the pairing process, see the DeviceEnumerationAndPairing sample.
#pragma region UI Code
#pragma endregion
#pragma region Device discovery
/// <summary>
/// Starts a device watcher that looks for all nearby Bluetooth devices (paired or unpaired).
/// Attaches event handlers to populate the device collection.
/// </summary>
void find_devs::StartBleDeviceWatcher()
{
// Additional properties we would like about the device.
// Property strings are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/ff521659(v=vs.85).aspx
auto requestedProperties = single_threaded_vector<hstring>({ L"System.Devices.Aep.DeviceAddress", L"System.Devices.Aep.IsConnected", L"System.Devices.Aep.Bluetooth.Le.IsConnectable" });
// BT_Code: Example showing paired and non-paired in a single query.
hstring aqsAllBluetoothLEDevices = L"(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
deviceWatcher =
Windows::Devices::Enumeration::DeviceInformation::CreateWatcher(
aqsAllBluetoothLEDevices,
requestedProperties,
DeviceInformationKind::AssociationEndpoint);
// Register event handlers before starting the watcher.
deviceWatcherAddedToken = deviceWatcher.Added({ get_weak(), &DeviceWatcher_Added });
deviceWatcherUpdatedToken = deviceWatcher.Updated({ get_weak(), &DeviceWatcher_Updated });
deviceWatcherRemovedToken = deviceWatcher.Removed({ get_weak(), &DeviceWatcher_Removed });
deviceWatcherEnumerationCompletedToken = deviceWatcher.EnumerationCompleted({ get_weak(), &DeviceWatcher_EnumerationCompleted });
deviceWatcherStoppedToken = deviceWatcher.Stopped({ get_weak(), &DeviceWatcher_Stopped });
// Start the watcher. Active enumeration is limited to approximately 30 seconds.
// This limits power usage and reduces interference with other Bluetooth activities.
// To monitor for the presence of Bluetooth LE devices for an extended period,
// use the BluetoothLEAdvertisementWatcher runtime class. See the BluetoothAdvertisement
// sample for an example.
deviceWatcher.Start();
}
/// <summary>
/// Stops watching for all nearby Bluetooth devices.
/// </summary>
void find_devs::StopBleDeviceWatcher()
{
if (deviceWatcher != nullptr)
{
// Unregister the event handlers.
deviceWatcher.Added(deviceWatcherAddedToken);
deviceWatcher.Updated(deviceWatcherUpdatedToken);
deviceWatcher.Removed(deviceWatcherRemovedToken);
deviceWatcher.EnumerationCompleted(deviceWatcherEnumerationCompletedToken);
deviceWatcher.Stopped(deviceWatcherStoppedToken);
// Stop the watcher.
deviceWatcher.Stop();
deviceWatcher = nullptr;
}
}
std::vector<Windows::Devices::Enumeration::DeviceInformation>::iterator FindUnknownDevices(hstring const& id)
{
}
fire_and_forget find_devs::DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
{
}
fire_and_forget find_devs::DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
{
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
auto deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id());
if (deviceInfo != UnknownDevices.end())
{
deviceInfo->Update(deviceInfoUpdate);
// If device has been updated with a friendly name it's no longer unknown.
}
}
}
fire_and_forget find_devs::DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
{
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
auto deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id());
if (deviceInfo != UnknownDevices.end())
{
UnknownDevices.erase(deviceInfo);
}
}
}
fire_and_forget find_devs::DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, IInspectable const&)
{
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
}
}
fire_and_forget DeviceWatcher_Stopped(DeviceWatcher sender, IInspectable const&)
{
// Access this->deviceWatcher on the UI thread to avoid race conditions.
auto lifetime = get_strong();
co_await resume_foreground(Dispatcher());
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
}
}
#pragma endregion
int main()
{
init_apartment();
Uri uri(L"http://aka.ms/cppwinrt");
printf("Hello, %ls!\n", uri.AbsoluteUri().c_str());
}
and, for completeness, this is pch.h
#pragma once
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Devices.Enumeration.h>
The code is, I know, not complete. I haven't created a DeviceWatcher, etc., but I am apparently blocked in that I can't get the get_weaks() to pass intellisense screening or to compile.
Any guidance from people who know about this stuff would be great.
Bear in mind: I, myself, pretty much don't know what's going on. Due to the complexity, from my Win32 Petzold-style background, of the example MS C++/WinRT UWP example. It has all kinds of stuff in the Solution Explorer. There are .idl files, a packages.config, a bunch of different Xaml files, some generated c++ files. All this stuff is beyond my understanding, and I have not been able to pick it up with any speed from the MS documentation I can find.
(All I have figured out is that C++/WinRT is some sort of a thing where there are generated header and perhaps other files that are supposed to make your C++ code look like it's directly accessing WinRT classes. And, I have seen MS write that you can use winRT in non-UWP applications. Otherwise, I am lost.)

Windows Phone app not receiving push notification from Parse.com

I have followed this tutorial on setting up Parse push notification in a Windows Phone app. This is my code:
public App() {
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached) {
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
// Initialize the Parse client with your Application ID and .NET Key found on
// your Parse dashboard
ParseClient.Initialize("grpTmrClet8K35yeXg2HQKK8wl59VeC9ijH0I0dn", "os8EfSFq9maPBtDJ91Mq0xnWme8fLANhttTPAqKu");
// After calling ParseClient.Initialize():
this.Startup += async (sender, args) =>
{
// This optional line tracks statistics around app opens, including push effectiveness:
ParseAnalytics.TrackAppOpens(RootFrame);
// By convention, the empty string is considered a "Broadcast" channel
// Note that we had to add "async" to the definition to use the await keyword
await ParsePush.SubscribeAsync("testchannel");
};
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private async void Application_Launching(object sender, LaunchingEventArgs e) {
await ParseAnalytics.TrackAppOpenedAsync();
}
When I send a push notification from the Parse dashboard it doesn't get received. I have tried running both on the emulator (Windows Phone 8.0) and device (8.1), with app in foreground, background and closed with the same negative result.
When I use a channel like "testchannel" above and use the segment options, the channel name appears in the dropdown list of options indicating that the app is at least connecting Parse, but it just wont receive the notifications.
Hope someone can help me identify what I am missing. Thanks in advance.
If you are developing a Windows Phone 8.1 app, make sure you've enabled toast notification in the manifest file.
I don't quite understand everything about Parse just yet, but this is what works for me.
In App.xaml.cs:
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
ParseClient.Initialize("wSjuNTbtjVLRaedXvOoaf9S5cTbkuQohTulNZ2vS", "nWZMhXRet9Wotlgikb9aUdKf5GFtRiMvduw7w68z");
}
We subscribe and enable analytics OnLaunched:
protected async override void OnLaunched(LaunchActivatedEventArgs e)
//Generated codes go here
await ParsePush.SubscribeAsync("testchannel");
await ParseAnalytics.TrackAppOpenedAsync();
That would simply do the trick. You should modify the code according to your needs. Hope this helps.

windows 8 app FileOpenPicker np file info

I'm trying to get some file information about a file the user select with the FileOpenPicker, but all the information like the path and name are empty. When I try to view the object in a breakpoint I got the following message:
file = 0x03489cd4 <Information not available, no symbols loaded for shell32.dll>
I use the following code for calling the FileOpenPicker and handeling the file
#include "pch.h"
#include "LocalFilePicker.h"
using namespace concurrency;
using namespace Platform;
using namespace Windows::Storage;
using namespace Windows::Storage::Pickers;
const int LocalFilePicker::AUDIO = 0;
const int LocalFilePicker::VIDEO = 1;
const int LocalFilePicker::IMAGES = 2;
LocalFilePicker::LocalFilePicker()
{
_init();
}
void LocalFilePicker::_init()
{
_openPicker = ref new FileOpenPicker();
_openPicker->ViewMode = PickerViewMode::Thumbnail;
}
void LocalFilePicker::askFile(int categorie)
{
switch (categorie)
{
case 0:
break;
case 1:
_openPicker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
_openPicker->FileTypeFilter->Append(".mp4");
break;
case 2:
break;
default:
break;
}
create_task(_openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
{
if (file)
{
int n = 0;
wchar_t buf[1024];
_snwprintf_s(buf, 1024, _TRUNCATE, L"Test: '%s'\n", file->Path);
OutputDebugString(buf);
}
else
{
OutputDebugString(L"canceled");
}
});
}
Can anybody see whats wrong with the code or some problems with settings for the app why it isn't work as expected.
First an explanation why you are having trouble debugging, this is going to happen a lot more when you write WinRT programs. First, do make sure that you have the correct debugging engine enabled. Tools + Options, Debugging, General. Ensure that the "Use Managed Compatibility Mode" is turned off.
You can now inspect the "file" option, it should resemble this:
Hard to interpret of course. What you are looking at is a proxy. It is a COM term, a wrapper for COM objects that are not thread-safe or live in another process or machine. The proxy implementation lives in shell32.dll, thus the confuzzling diagnostic message. You can't see the actual object at all, accessing its properties requires calling proxy methods. Something that the debugger is not capable of doing, a proxy marshals the call from one thread to another, that other thread is frozen while the debugger break is active.
That makes you pretty blind, in tough cases you may want to write a littler helper code to store the property in a local variable. Like:
auto path = file->Path;
No trouble inspecting or watching that one. You should now have confidence that there's nothing wrong with file and you get a perfectly good path. Note how writing const wchar_t* path = file->Path; gets you a loud complaint from the compiler.
Which helps you find the bug, you can't pass a Platform::String to a printf() style function. Just like you can't with, say, std::wstring. You need to use an accessor function to convert it. Fix:
_snwprintf_s(buf, 1024, _TRUNCATE,
L"Test: '%s'\n",
file->Path->Data());

RX throttle on WinRT TemplatedControl

I have some problems with thread synchronization in my Templated control (trying to do a AutoComplete control)
Inside my control I have this code:
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
var searchTextBox = GetTemplateChild("SearchTextBox") as TextBox;
if (searchTextBox != null)
{
var searchDelegate = SearchAsync;
Observable.FromEventPattern(searchTextBox, "TextChanged")
.Select(keyup => searchTextBox.Text)
.Where(TextIsLongEnough)
.Throttle(TimeSpan.FromMilliseconds(500))
.Do(ShowProgressBar)
.SelectMany(searchDelegate)
.ObserveOn(Dispatcher)
.Subscribe(async results => await RunOnDispatcher(() =>
{
IsInProgress = false;
SearchResults.Clear();
foreach (var result in results)
{
SearchResults.Add(result);
}
}));
}
}
And it is complaining that inside my ShowProgressBar method I'm trying to access code that was marshalled by another thread.
If I comment out the Throttle and the ObserveOn(Dispatcher) it works just fine, but it does not throttle my service calls as I want to.
If I only comment out the Throttle part, Nothing happens at all.
Asti's got the right idea, but a far better approach would be to provide the IScheduler argument to Throttle instead:
// NB: Too lazy to look up real name
.Throttle(TimeSpan.FromMilliseconds(500), CoreDispatcherScheduler.Instance)
This will make operations below it happen on the UI thread (including your ShowProgressBar), up until the SelectMany.
Every dependency object requires that any changes to dependency properties be made only on the Dispatcher thread. The Throttle is using a different scheduler, hence making any changes to the UI in a subsequent Do combinator would result in an access exception.
You can resolve this by:
Add an ObserveOnDispatcher before any actions which cause side-effects on the Dispatcher. Optionally use another scheduler down the pipeline.
Use Dispatcher.Invoke to execute side-effects through the dispatcher. E.g., .Do(() => Dispatcher.Invoke(new Action(ShowProgressBar)))