Adventures in UWP – Prism (more Unity than Prism)

Prism is a well used framework in WPF and it’s also available in UWP. So let’s try it out. We’re going to start by looking at switching the default generated (blank) UWP application into one which uses Prism or more specifically Unity and Prism’s navigation functionality.

  • Create a Blank UWP application
  • From Nuget install the package Prism.Unity (I’m using v6.3.0)
  • Edit App.xaml.cs and change the base class from Application to PrismUnityApplication (yes we’ll use Unity for this test), don’t forget to add using Prism.Unity.Windows;
  • Remove all generated code from App.xaml.cs except for the constructor
  • Open App.xaml and change it from using Application to PrismApplication, for example
    <windows:PrismUnityApplication
        x:Class="MathsTest.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:MathsTest"
        xmlns:windows="using:Prism.Unity.Windows"
        RequestedTheme="Light">
    
    </windows:PrismUnityApplication>
    
  • Add the following bare bones method (yes it’s not handling possible startup states etc. as I wanted to reduce this code to the minimum)
    protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
    {
       NavigationService.Navigate("Main", null);
       return Task.FromResult(true);
    }
    
  • By default the UWP project will have created a MainPage.xaml but Prism’s navigation code expects this to be in a Views folder, so create a Views folder in your solution and move MainPage.xaml into this Views folder.

    If you see an exception along the lines of “The page name does not have an associated type in namespace, Parameter name: pageToken” then you’ve probably not got a view with the correct name within the Views folder. Don’t forget to update the XAML and the xaml.cs files to include Views in the name space, i.e. TestApp.Views.MainPage

At this point we have UWP running from Prism.

Internal error 500, code 0x80070021 in IIS

Whilst setting up a new build server I came across the following error internal error 500, code 0x80070021 from IIS (I was setting up CruiseControl.net, but I assume this isn’t specific to that application).

It seems this is down to the handlers being locked in IIS, running the following fixed this issue

%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/handlers

Beware those async void exceptions in unit tests

This is a cautionary tale…

I’ve been moving my builds to a new server box and in doing so started to notice some problems. These problems didn’t exist on the previous build box and this might be down to the updates versions of the tools, such as nant etc. I was using on the new box.

Anyway the crux of the problem was I was getting exceptions when the tests were run, nothing told me what assembly or what test, I just ended up with

NullReference exceptions and a stack trace stating this

System.Runtime.CompilerServices.AsyncMethodBuilderCore.b__0(System.Object)

Straight away it looks like async/await issues.

To cut a long story short.

I removed all the Test assemblies, then one by one place them back into the build, running the “test” target in nant each time until I found the assembly with the problems. Running the tests this way also seemed to report more specifics about the area of the exception.

As we know, we need to be particularly careful handling exceptions that occur within an async void method (mine exist because they’re event handlers which are raised upon property changes in a view model).

Interestingly when I ran the Resharper Test Runner all my tests passed, but switching to running in the tests in Debug showed up all the exceptions (ofcourse assuming that you have the relevant “Exceptions” enabled within Visual Studio). The downside of this approach, ofcourse, is that I also see all the exceptions that are intentionally tested for, i.e. ensuring my code exceptions when it should. But it was worth it to solve these problems.

Luckily none of these exceptions would have been a problem in normal running of my application, they were generally down to missing mocking code or the likes, but it did go to show I could be smug in believing my tests caught every issue.

net share is my friend

I recently had to set-up some shares on a server box using File Explorer and the share menu option, but after a reboot they all disappeared.

Note: I’m not concerned by this behaviour, of losing the shares, as it’s probably down to some security policy but every now and then it’s so much easier having the shares available to work from when I need to deploy apps etc.

Anyway, using net share in a batch file saves the day.

Just run

net share

to view the current shares on your machine.

Now to create a share, simply use

net share DEPLOYMENT=d:\mydeployment /GRANT:EVERYONE, READ

In this case I’m actually creating a READ only share with access granted to everyone. The string to the left of the = operator is the sharename (i.e. what you’ll see or use to access the share) obviously the right hand side is the location on the machine the share points to.

Obviously EVERYONE might by less than great in terms of security, so instead you can GRANT individual user’s access. The permission can be READ | CHANGE | FULL, see the output of net share /?

The syntax of this command is:

NET SHARE
sharename
          sharename=drive:path [/GRANT:user,[READ | CHANGE | FULL]]
                               [/USERS:number | /UNLIMITED]
                               [/REMARK:"text"]
                               [/CACHE:Manual | Documents| Programs | BranchCache | None]
          sharename [/USERS:number | /UNLIMITED]
                    [/REMARK:"text"]
                    [/CACHE:Manual | Documents | Programs | BranchCache | None]
          {sharename | devicename | drive:path} /DELETE
          sharename \\computername /DELETE

Trying out Refit (a REST client library)

REST is cool in that it’s lightweight and simple to use but lacks a lot of the tooling etc. that SOAP/XML has.

In .NET we have libraries such as ServiceStack (and others) to enable generation of REST services to be fairly painless, there are also a few client frameworks out there, but for this post I’m looking at Refit which (as the documentation states) is automatically type-safe and available in .NET standard 1.4 which also includes Xamarin, UWP and desktop. So pretty universal in it’s availability.

Show me the code!

Enough chat, let’s get into the code. I’m going to use ServiceStack to generate a simply REST service, the default one is the “Hello” service, which in code looks like this

[Route("/hello/{Name}")]
public class Hello : IReturn<HelloResponse>
{
   public string Name { get; set; }
}

public class HelloResponse
{
   public string Result { get; set; }
}

and this will be called using http://127.0.0.1:8088/hello/World which in turn returns (in JSON format)

{"Result":"Hello, World!"}

All pretty simple.

One thing we will do, is switch ServiceStack to use JSON be default, so in the MyService generated code we’ll add an AddHeader attribute, so it will look like this

public class MyServices : Service
{
   [AddHeader(ContentType = MimeTypes.Json)]
   public object Any(Hello request)
   {
      return new HelloResponse { Result = "Hello, {0}!".Fmt(request.Name) };
   }
}

Creating our client

Fire up Visual Studio and create a console application (I’ve targeted .NET 4.6), then add Refit via NuGet.

As we already have the HelloResponse class from our ServiceStack sample application, we can just copy that into our Refit application, or visit https://quicktype.io/ and paste {“Result”:”Hello, World!”} into the JSON edit box on the left of the site and it’ll create the class for us. So using either method we need to add the JsonProperty so it now looks like this in our Refit app.

public class HelloResponse
{
   [JsonProperty("Result")]
   public string Result { get; set; }
}

Next up we need create an interface that calls our REST service. We know, having written/generated the code for the service that there’s a Hello class that defines the route and response, but we won’t be copying this, instead Refit likes to use methods returning a Task (which makes sense being a web service call) so create (in your Refit app.) the following

public interface IHelloService
{
   [Get("/hello/{name}")]
   Task<HelloResponse> SayHello(string name);
}

Note we create an interface and that the route is within the Get attribute points to our Hello endpoint. Next we created a method to be called to contact our endpoint at the aforementioned route. This is the main area where we actually have to do any coding for this example to work.

Let’s now create the client code

var svc = RestService.For<IHelloService>("http://127.0.0.1:8088");
var response = svc.SayHello("World");

and that’s it – obviously you’ll need to await or Result etc. to get the actually HelloResponse object, but that’s all there is to this (admittedly very simple example).

As you can see the RestService.For method creates an instance of an IHelloService for us acting as a transparent proxy through to the service.

References

The automatic type-safe REST library for Xamarin and .NET
Exploring refit, an automatic type-safe REST library for .NET Standard

Writing your first Azure Function

With serverless all the rage at the moment and AWS Lambda’s and Azure Functions offering us easy routes into serverless in the cloud, I thought it about time I actually looked at what I need to do to create a simple Azure function.

Creating a function using the portal

  • Log into https://portal.azure.com/
  • From the Dashboard select New
  • Select Function App
  • Supply an App name, set your subscription, location etc. then press Create (I pinned mine the dashboard also using the Pin to dashboard checkbox)
  • After a while (it’s not instant) you’ll be met with options for your Function Apps, Functions, Proxies and Slots.
  • Click in the + of functions
  • Select HttpTrigger – C# or whatever your preferred language is, other triggers can be investigated later but this basically creates a simple REST like function, perfect for quick testing
  • Give your function a name and for now leave the Authorization level alone

I used the default name etc and got the following code generated for me by Azure’s wizard.

Note: Whilst there is some information out there on renaming Azure functions, the current portal doesn’t seem to support this, so best to get your name right first time or be prepared to copy and paste code for now into a new function.

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    name = name ?? data?.name;

    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}

This is basically the Hello World of Azure functions. If you run it from the portal you’ll see the output “Hello Azure” as well as logs output. The request box allows you to edit the “name” field which is sent to the function.

By default the authorization level is Function, which basically means that a key is required to run this function. If you click the </> Get function URL link, Azure will supply the fully URL, minus the request payload and this will include the text code=abc123 where abc123 represents a much longer key.

Note: you can find your keys also via the Manage option below the Functions list on the left of the portal. Click the “Click to show” on Function Keys default.

We can remove the requirement for the key and make the function accessible to anonymous users by selecting the Integrate option under the Function name on the left list of the portal and changing Authorization level to Anonymous.

Beware that you’ll be allowing anyone to call your function with the Anonymous option which ultimately ends with your account paying for usage.

Now, once you have the URL for you function just append &name=World to it and navigate to the function via your browser (remove the code= text and don’t bother with the & for anonymous access).

Creating and deploying from Visual Studio 2017

If you have the Azure tools installed then you can create Azure functions directly in Visual Studio (I’m using 2017 for this example).

  • File | New Project
  • Select Cloud | Azure Functions (or search for it via the search box)
  • Name your project, mine’s HelloWorldFunctions
  • At this point I build the project to bring in the NuGet packages required – you can obviously do this later
  • Add a new item to the project, select Azure Function, mine’s named Echo.cs
  • Select HttpTrigger to create a REST like function
  • Leave Access rights to Function unless you want Anonymous access

When completed, we again get the default Hello Azure/World sample code. We’re not going to bother changing this at this time, but instead will look to deploy to Azure. But first, let’s test this function in Visual Studio (offline). Simply click the run button and a console window will open with a web server running mimicking Azure, mine creates makes the function available via

http://localhost:7071/api/Echo

If we run this from a web browser and add the ?name=, like this

http://localhost:7071/api/Echo?name=Mark

we’ll get “Hello Mark” returned.

Okay, so it’s working fine, let’s deploy/publish it.

  • Right mouse click on the project
  • Select Publish…
  • Either create new or select existing (if you already have an app), you may need to enter your account details at this point
  • In my case I created the application via the Portal first so I selected existing and then select my application from the options available
  • Press OK
  • Eventually the Publish button will enable, then press this

This will actually publish/deploy the DLL with your Azure function(s) to the Azure application. When you view the function in the Azure Portal you won’t see any source code as you’ve actually just deployed the compiled DLL instead.

In the portal, add your Request body, i.e.

{
   "name" : "Azure"
}

and run from the Portal – this is basically a replica (at the functional level) of the portal’s created default function.

Let’s look at the code

I’m going to show the code created via the Visual Studio template here

public static class Echo
{
   [FunctionName("Echo")]
   public static async Task<HttpResponseMessage> Run(
      [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
      HttpRequestMessage req, TraceWriter log)
   {
      log.Info("C# HTTP trigger function processed a request.");

      // parse query parameter
      string name = req.GetQueryNameValuePairs()
         .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
         .Value;

      // Get request body
      dynamic data = await req.Content.ReadAsAsync<object>();

      // Set name to query string or body data
      name = name ?? data?.name;

      return name == null ? 
        req.CreateResponse(HttpStatusCode.BadRequest, 
           "Please pass a name on the query string or in the request body")
       : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
   }
}

If you’ve used any C# or Java HTTP like functions, this will all seem pretty familiar.

Our function is passed two parameters, the first being the HTTP request message and the second is the logging object. Obviously the logger is pretty self explanatory.

The HttpRequestMessage contains all those sorts of things we’d expect for an HTTP request, i.e. query name parameters, headers, content etc. and like many similar types of functions we return an HTTP response along with a result code.

Adventures in UWP – Getting Started

For a while now I’ve wanted to do something in UWP (Universal Windows Platform).

UWP always gives me the “uncanny valley” sort of feeling; it looks like WPF and looks like a standard Windows .NET application, but it also has that feeling on the unknown about it. To illustrate what I mean, UWP application compile to an EXE, but anyone used to Windows programming will probably double click on the EXE and find that Windows responds with a message box stating “This application can only run in the context of an app container”.

We’ll cover this soon enough, but let’s start our adventure with the classic Hello World type example and look at the basic parts of a UWP application and using Visual Studio 2017 to run the application etc.

Versions etc.

First off, I’m using Windows 10.0.15063.0 and Visual Studio 2017, version 15.2 (26430.16). I state this upfront because I’ve found books/posts talking about previous versions telling us to expect this file and this dialog when creating a new project, so what you see may differ from what I describe here, depending upon your versions.

Creating our project

In Visual Studio, carry out the following

  1. File | New Project
  2. Visual C# | Windows Universal
  3. Select Blank App (Universal Windows)
  4. Name it HelloWorld
  5. You’ll be prompted to choose a target version and minimum version, leave these as defaulted for now

Navigating the project

Properties

Within the Properties section is the usual AssemblyInfo.cs, but also the Default.rd.xml. This is used to contain runtime directives (hence .rd.). This allows us to specify elements within our program that are available for reflection.

Reference

Unlike non-UWP applications, the References have only two items (excluding the Analyzers). Microsoft.NETCore.UniversalWindowsPlatform and Universal Windows.

Assets

By default the Assets folder contains seven png images. Including store logo and splash screen. These are templates (if you like) for your own images. Every one of the images is a square with a cross in it – so you’ll know pretty quickly if you’ve not supplied an image/logo/splash screen for some area.

App.xaml

Like WPF, we have an App.xaml (and ofcourse the App.xaml.cs code behind). The code behind has a fair bit more code within it, unlike WPF. Default code is there for us to handle state loading during the application launch, a point to save state when the application is suspended etc. Also, unlike WPF, the MainWindow (in this case MainPage) is navigated to via the OnLaunched code as opposed to being declared in the App.xaml file like WPF.

HelloWorld_TemporaryKey.pfx

A temporary key is created for us. As UWP is aimed at being downloaded and installed from the Windows Store (or side loaded) this requires the application to be signed, hence we’re given the starting point for this.

MainPage.xaml

MainPage.xaml and it’s code behind contain minimal XAML and code (like a standard WPF control). UWP tends to class these controls as Pages (reminds me of Silverlight).

Package.appxmanifest

Finally we come to the application manifest. This allows us to set up things like the application’s display name, the rotations supported (for tablet/phone type devices). We can assign our assets to specific scenarios, such as for tiles, app. icons and so on. We’ll also need to declare what capabilities the application needs access to. Sort of standard mobile phone development requirements, i.e. this application will require Bluetooth etc.

Note: It’s best to reduce the capabilities to the bare minimum required as some user’s may prefer to lock down the access an application has.

What happens if we run the application now?

So if we want to run the application, you’ll notice that (at least on my install of Visual Studio) there the run button on the toolbar with Local Machine shown (mine’s also defaulted to x86 instruction set). From the drop down we also have Simulator, Remote Machine, Device as well as a bunch of Mobile Emulators of different screen sizes.

The emulators obviously allow us to view our application on a mobile phone or tablet like sized device.

Remote Machine allows us to run the application remotely, so for example on a Windows tablet, but without needing to install it directly etc.

The simulator is a virtual device or maybe better thought of as a remote desktop. The odd thing is that you’re really remote desktop-ing into your own machine, so changes to the simulator affect your machine.

So, let’s choose Local Machine, then we’re doing the equivalent of running a “standard” windows application. You’ll notice a square with a cross in it displayed, this is the SplashScreen.scale-200.png supplied by the project template within our Assets folder. Change this and then re-run to confirm.

Once running our application is, as expected, a blank application, but before we move onto actually writing some code/designing the UI, when we ran the application Visual Studio actually installed the application for us in the Start Menu, under Recently Added you should see HelloWorld (if you followed my naming for the application). If you attempt the run the EXE within the build folder, you’ll get the message box stating “This application can only run in the context of an app container”, however from the Start Menu, the application will be correctly run from a container.

Finally for this section, when you run the application via Visual Studio you’ll see four icons on your main page, these include tools to view the visual tree of a selected item at runtime and enable selected option, display layout adorners and a track focused element tool.

These, by default, are hidden outside of the debugger, but we can also hide within the debugger experience by selecting Tools | Options | Debugging | General, then locate Enable UI Debugging Tools for XAML and deselect this option.

The splash screen

As mentioned previously, we define the splash screen image (or edit the existing) within the Assets, as this is assigned via the manifest. UWP automatically displays the splash screen for us over the application Window and within App.xaml.cs, the OnLaunched method, when Window.Current.Activate() is called, the splash screen will be removed (obviously it will not immediately happen as the Windows message will need to be sent through, but it’s at this point the UWP application then “properly” starts your application. Hence within OnLaunched, is the place to restore state or setup anything prior to the splash screen being removed.

Note: Like Windows Services, your application is expected to start within a certain amount of time or it’s perceived as failing to start. I’ve read this time is approximately 15 seconds. So you’ll need to be a little more creative if loading your application takes longer than this, i.e. run code on a non-blocking thread or simply lazy load state etc.

The Humanizer

I don’t really have much to say about the Humanizer library that’s not already written on their Github readme.

This post is more of a reminder post, just to remind me about the library because the name of it eluded me the other day when I wanted to use it.

So what is Humanizer?

If you’ve got strings, enums, dates, times (and more) that you need to convert to a more human readable string, then Humanizer can help. Equally if you have a string that you want to make less human readable you can use Humanizer (bare with me, the less human readable might be of use).

An example

I’ll use the real world scenario I needed to use Humanizer on.

I have data coming from a web service which returns field/property names and values. The names are in standard camel case, i.e. eligibilityFlag. Now this is fine, but I wanted the end user to see these names in a more human readable way, i.e. “eligibilityFlag” should display as “Eligibility flag”. It’s just nicer, looks better and is more readable for the end user.

Ofcourse, it’s not too difficult to write the code to do this yourself, but why bother when you can fire up Nuget or the Package Manager Console and locate the Humanizer package or run Install-Package Humanizer.

Just using the following

// don't forget using Humanizer

Console.WriteLine("eligibilityFlag".Humanize());

and the output will be Eligibility flag.

We can easily convert this back to the camel case computer style text using

Console.WriteLine("Eligibility flag".Dehumanize().Camelize());

Humanizer can also help with numbers to strings, for example convert numbers to works or to an easier to read format. If we have the value 123456 we might like to output and 123.456K or maybe as one hundred and twenty-three thousand four hundred and fifty-six using

Console.WriteLine(123456.ToWords());
Console.WriteLine(123456.ToMetric());

we can convert the metric representation back using

Console.WriteLine("123.456k".FromMetric());

Folding expressions in C++ 17

Setup your dev tools to use C++ 17

Using CLion (or CMake) and setting the CMakeLists.txt CMAKE_CXX_STANDARD to

set(CMAKE_CXX_STANDARD 17)

allows us to use C++ 17 features.

In CLion the intellisense/editor will show folding expressions with red underlines, i.e. as errors in the current release, however the code will compile

Folding Expressions

Basically folding expressions allow us to write code which takes one or more arguments and applies operators to them to create a return value.

In C++ terms, folding expressions take variadic template arguments and unpack the arguments using unary or binary operators to create a return value.

The syntax for folding expressions, is as follows

Syntax (as taken from http://en.cppreference.com/w/cpp/language/fold).

  • unary right fold (pack op …)
  • unary left fold (… op pack)
  • binary right fold (pack op … op init)
  • binary left fold (init op … op pack)

Let’s look at some examples to make things clearer using this syntax.

Unary right fold

The following is a simple summation method using unary right fold syntax

template<typename... Args>
auto unary_right_fold(Args... args) {
    return (args + ...);
}

Unary left fold

The following is a simple summation method using unary left fold syntax

template<typename... Args>
auto unary_left_fold(Args... args) {
    return (... + args);
}

Binary right fold

The following is a simple summation + 1 method using binary left fold syntax

template<typename... Args>
auto binary_right_fold(Args... args) {
    return (args + ... + 1);
}

Binary left fold

The following is a simple 1 + summation method using binary left fold syntax

template<typename... Args>
auto binary_left_fold(Args... args) {
    return (1 + ... + args);
}

threads, promises, futures, async, C++

The only C++ application I now maintain used a single thread to handle background copying and it was fine, but anything more than that and it becomes a little more complex to maintain, especially when compared to threading in C#, such as TPL, Parallel library and async/await.

Now whilst these new features/libraries are not in the same “ease of use” area as those C# classes etc. they are nevertheless a massive step forward.

From what I can tell, we have four different multi-threaded operations (I think that’s the best way to put it). I’m not talking locking, or other forms of synchronization here.

std::thread

So at the most basic level we have the std::thread which is extremely simple to use, here’s an example

auto t = std::thread([]
{
   // do something in a thread
});

We can block (or wait) until the thread has completed using t.join();, but there’s other possibilities for interacting with our thread.

std::future and std::promise

Futures and promises are two sides of the same coin, so to speak. A promise allows us to return state from a thread. Whereas a future is for reading that returned state.

In other words, let’s think of it in this, fairly simple way – we create a promise that really says that at some time there will be a state change or return value from thread. The promise can be used to get a std::future, which is the object that gives us this return result.

So we’ve got the equivalent of a simple producer/consumer pattern

auto promise = std::promise<std::string>();
auto producer = std::thread([&]
{
   // simulate some long-ish running task
   std::this_thread::sleep_for(std::chrono::seconds(5));
   promise.set_value("Some Message");
});

auto future = promise.get_future();
auto consumer = std::thread([&]
{
   std::cout << future.get().c_str();
});

// for testing, we'll block the current thread
// until these have completed
producer.join();
consumer.join();

Note: In the example above I’m simply using a lambda and passing reference to all variables in scope via the capture, using [&], as a capture list is required to access the promise and future outside of the lambdas.

In this example code we simply create a promise and then within the first thread we’re simulating a long-ish running task with the sleep_for method. Once the task is complete we set_value on the promise which causes the future.get() to unblock, but we’ve jumped ahead of ourselves, so…

Next we get the future (get_future) from the promise and to simulate a a producer/consumer we spin up another thread to handle any return from the promise via the future.

In the consumer thread, the call to future.get() will block that thread until the promise has been fulfilled.

Finally, the code calls producer.join() and consumer.join() to block the main thread until both producer and consumer threads have completed.

std::async

The example for the promise/future combination to create a producer consumer can be simplified further using the std::async which basically deals with creating a thread and creating a future for us. So let’s see the code for the producer/consumer now with the std::async

std::future<std::string> future = std::async([&]
{
   std::this_thread::sleep_for(std::chrono::seconds(5));
   return std::string("Some Message");
});

auto consumer = std::thread([&]
{
   std::cout << future.get().c_str();
});

consumer.join();

In the above we’ve done away with the promise and the first thread which have both been replaced with the higher level construct, std::async. We’ve still got a future back and hence still call future.get() on it, but notice how we’ve also switch to returning the std::string and the future using the template argument to match the returned type.

We’re not actually sure if the code within the async lambda is run on a new thread or run on the calling thread, as the async documentation states…

“The template function async runs the function f asynchronously (potentially in a separate thread which may be part of a thread pool) and returns a std::future that will eventually hold the result of that function call.”

So the async method may run the code on a thread or deferred. Deferred meaning the code is run when we call the future’s get method in a “lazy” manner.

We can stipulate whether to run on a thread or as deferred using an std::async overload

std::future<std::string> future = 
   std::async(std::launch::deferred, [&]
   {
   });

In the above we’ve deferred the async call and hence it’ll be run on the calling thread, alternatively we could stipulate std::launch::async, see std::launch.

What about exceptions?

If an exception occurs in async method or the promise set_exception is called in our producer/consumer using a promise. Then we need to catch the exception in the future (call to get()). Hence here’s an example of the async code with an exception occuring

std::future<std::string> future = std::async([&]
{
   throw std::exception("Some Exception");
   return std::string("Some Message");
});

auto consumer = std::thread([&]
{
   try
   {
      std::cout << future.get().c_str();
   }
   catch(std::exception e)
   {
      std::cout << e.what();
   }
});

consumer.join();

Here we throw an exception in the async lambda and when future.get is called, that exception is propagated through to the consumer thread. We need to catch it here and handle it otherwise it will leak through to the application and potentially crash the application if not handled elsewhere.