<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>The Brain Dump</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/benwilli/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/benwilli/feed.xml</link>
    <description>My brain poured out on paper (or so to speak)</description>
    <lastBuildDate>Tue, 07 May 2019 14:03:23 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Blog migration</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/blog-migration</link>
      <pubDate>Tue, 07 May 2019 09:03:23 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/?p=3135</guid>
      <description><![CDATA[Hi all,My blog is moving to a new location (merging with my personal project blog) :...]]></description>
      <content:encoded><![CDATA[<p>Hi all,<p>My blog is moving to a new location (merging with my personal project blog) : <a href="https://blog.negativeeddy.com">https://blog.negativeeddy.com</a><p>New posts will be going to this new location. I’ve migrated the old posts over there as well.</p>]]></content:encoded>
    </item>
    <item>
      <title>Raw threads and async lambdas</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/raw-threads-and-async-lambdas</link>
      <pubDate>Mon, 27 Aug 2018 12:59:44 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/?p=2935</guid>
      <description><![CDATA[Using async methods/lambdas where they are not expected causes unexpected problems. The typical...]]></description>
      <content:encoded><![CDATA[Using async methods/lambdas where they are not expected causes unexpected problems. The typical example I discuss with people is <a href="https://blogs.msdn.microsoft.com/pfxteam/2012/02/08/potential-pitfalls-to-avoid-when-passing-around-async-lambdas/">TaskFactory.StartNew()</a> because its an easy way to create Tasks and some people reach for that instead of Task.Run(), but I recently came across some code hitting the same problem while creating threads the traditional way.

In this scenario, the code was intended to create some child threads that poll a resource. That resource would sometimes be changed and the master thread would Abort() the child threads and create new ones polling the new resource. But there was a thread leak. Sometimes threads could continue to run after they should have been aborted.

A simplified example looks like this in a console application (I’m not creating the new threads after the abort because its not relevant to the bug in the logic).

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/capture20180827101340802.png"><img width="594" height="272" title="capture20180827101340802" alt="capture20180827101340802" src="https://msdnshared.blob.core.windows.net/media/2018/08/capture20180827101340802_thumb.png" border="0" /></a>

We are simply starting two threads, waiting 1 second, and then aborting them. We assume they will stop and not output anything after the “Press ENTER” line. But notice that the two thread functions are asynchronous. What does that mean? As <a href="https://blogs.msdn.microsoft.com/benwilli/2015/09/10/tasks-are-still-not-threads-and-async-is-not-parallel/">I’ve discussed before</a> you can’t really make any assumptions about the internals of the async code you are calling. You can only know what you are doing yourself around the async operation. What we are doing here is “Start this asynchronous operation on another thread.” We don't really know when this method will end, or even if it will end on our thread.

So when does our thread end? Can we even abort the operation this way? Not reliably, no.

If the code happens to look like this, we can abort it.

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/capture20180827102020875.png"><img width="366" height="226" title="capture20180827102020875" alt="capture20180827102020875" src="https://msdnshared.blob.core.windows.net/media/2018/08/capture20180827102020875_thumb.png" border="0" /></a>

But that's only because there is no asynchrony actually going on. This will run synchronously on the original thread that called it. But that's pretty uncommon. More likely there is some asynchrony going on inside it like this

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/capture20180827102720938.png"><img width="356" height="233" title="capture20180827102720938" alt="capture20180827102720938" src="https://msdnshared.blob.core.windows.net/media/2018/08/capture20180827102720938_thumb.png" border="0" /></a>

In this case there is an asynchronous delay. This means that all of the iterations of the loop after 0, will happen as asynchronous continuations. Where will they run? It depends on the context. In this example, a console application, they will run on a random thread pool thread.

That means that when I try to abort the thread I created, I’m just aborting the initial thread which is handling the first portion of the method. If the application gets to the await before it gets to the abort, the continuation will already scheduled and will go on oblivious to the fact that the original thread gets aborted. I can’t abort this method using Thread.Abort() because method isn’t just one thread.

Here is what the output looks like. You can see that until the abort happens (immediately before the “Press ENTER” text) the threads are pumping out even and odd numbers. After the abort, the PrintEvenNumbers method is happily continuing its way into infinity.

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/capture20180827103138495.png"><img width="415" height="467" title="capture20180827103138495" alt="capture20180827103138495" src="https://msdnshared.blob.core.windows.net/media/2018/08/capture20180827103138495_thumb.png" border="0" /></a>
<h3>How to avoid this?</h3>
<ul>
 	<li>Stick with Tasks and avoid raw Thread code if you can help it. The threading APIs predate the Task/Async APIs by a decade. Mixing the two can result in bugs like this one unless you are extra careful. <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run">Task.Run</a>() is your friend for spawning/managing new Tasks, and it is async lambda friendly.</li>
 	<li>Avoid Thread.Abort() like the plague. There are some unusual cases where it makes sense, but the vast majority of the times I see it, I consider it to be a bug. .NET provides a very clean cooperative cancellation mechanism that is simple and thread safe (the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken">CancellationToken</a>) which should be used instead to signal a child task to tear itself down cleanly and predictably.</li>
 	<li>More on <a href="https://blogs.msdn.microsoft.com/pfxteam/2012/02/08/potential-pitfalls-to-avoid-when-passing-around-async-lambdas/">why async lambdas behave this way</a> from the .NET Framework team</li>
</ul>
The sample code above is available <a target="_blank" href="https://gist.github.com/negativeeddy/63c1ee8506fb7c81e038180a9fc62465" rel="noopener">here</a>]]></content:encoded>
    </item>
    <item>
      <title>Accessing a .NET bot's state via dependency injection</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/accessing-a-dotnet-bots-state-via-dependency-injection</link>
      <pubDate>Tue, 13 Feb 2018 10:46:04 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/?p=2835</guid>
      <description><![CDATA[[NOTE: This post refers to version 3 of the Bot Framework]

When using the .NET BotBuilder SDK’s...]]></description>
      <content:encoded><![CDATA[[NOTE: This post refers to version 3 of the Bot Framework]

When using the <a href="https://docs.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-quickstart">.NET BotBuilder SDK’s</a> dialog system, you can access the bot state using the dialog context, but what if you don’t have the dialog context handy?

You have two options
<ol>
 	<li>Pass the context around all the time</li>
 	<li>Use the already built in IoC container to get the bot state.</li>
</ol>
With v3 of the Microsoft Bot Builder SDK, the <a href="https://docs.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-state">documentation</a> describes how to configure your bot to store its bot state data in either Azure Table storage or in a Cosmos DB. Notice that in the documentation, you configure the storage providers via Autofac registration (which Bot Builder uses internally to manage its various services). So you should be able to get them back from the Autofac container via dependency injection.

To move into a dependency injection model you need to load your dialogs from the dependency container too. That way, any dependencies (like the bot state) will be injected automatically.

In this example I have a few key components to demonstrate the pattern
<ul>
 	<li><strong>IBotData</strong> - this interface is defined, implemented, and <a href="https://github.com/Microsoft/BotBuilder/blob/master/CSharp/Library/Microsoft.Bot.Builder.Autofac/Dialogs/DialogModule.cs#L173">registered by the BotBuilder SDK automatically</a>. Whenever you post an Activity to a dialog chain, the SDK <a href="https://github.com/Microsoft/BotBuilder/blob/1f144aa4a8bfc1e7fb4d4914bb95072406150a0f/CSharp/Library/Microsoft.Bot.Builder/Dialogs/DialogTask.cs#L476">loads the IBotData, process the post, then saves the IBotData</a>. So if we put a dependency on this, we will always have the current botstate loaded and available while our dialog or service is running (including user, conversation and private conversation data)</li>
 	<li><strong>RootDialog</strong> – this is the main dialog, it has a dependency on the IUserData service. This dialog doesn’t know anything about bot state. It just uses the IUserData service to load and save a normal .NET property. The IUserData service will be injected into the constructor parameter automatically.</li>
 	<li><strong>UserData</strong> – this class is a facade over the bot state. It implements the IUserData service. It depends on the IBotData service, but has no concept of dialogs or dialog contexts. This provides a strongly typed property-like experience for any consumer that want to read/write data that is persisted in bot state</li>
 	<li><strong>BotModule</strong> – the class that registers RootDialog and UserData with the IoC container</li>
</ul>
The BotModule registers the RootDialog class so that we can resolve it and have its dependencies injected into the constructor.

<a href="https://msdnshared.blob.core.windows.net/media/2018/02/clip_image00118.png"><img width="358" height="85" title="clip_image001" alt="clip_image001" src="https://msdnshared.blob.core.windows.net/media/2018/02/clip_image001_thumb4.png" border="0" /></a>

It then registers the UserData class and marks it as non-serializable. The UserData class doesn’t have any data of its own and just passes through to the IBotData service. The BotBuilder SDK will not attempt to serialize any objects registered with the key Key_DoNotSerialize.

<a href="https://msdnshared.blob.core.windows.net/media/2018/02/clip_image0022.png"><img width="769" height="121" title="clip_image002" alt="clip_image002" src="https://msdnshared.blob.core.windows.net/media/2018/02/clip_image002_thumb2.png" border="0" /></a>

Finally, we need to change how we invoke the RootDialog. We cannot use the traditional Conversation.SendAsync() method because inside that method, the BotBuilder SDK creates a new IoC scope. We need to have our RootDialog and the BotBuilder services in the same scope. To achieve this we will create the scope ourselves and the post to the bot in the same way that SendAsync() does.
<h6>Specifically we need to</h6>
<ol>
 	<li>Create a delegate that will resolve a new RootDialog.</li>
 	<li>Register that delegate for use by the bot (in this scope)</li>
 	<li>Resolve the IPostToBot service.</li>
 	<li>Post the current activity to the IPostToBot service.</li>
</ol>
<a href="https://msdnshared.blob.core.windows.net/media/2018/02/image214.png"><img width="801" height="303" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2018/02/image_thumb174.png" border="0" /></a>

Once this is all in place, the bot SDK will use our RootDialog generated from the IoC container as the root of the dialog stack. Our dialog can now read and write properties naturally and they will be read from and written to the underlying bot state provider automatically.

The full solution is available at <a href="https://github.com/negativeeddy/BotStateDIExample">https://github.com/negativeeddy/BotStateDIExample</a>

<em>(edit: added description of IBotData)</em>]]></content:encoded>
    </item>
    <item>
      <title>Async Main() is available, but hidden</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/async-main-is-available-but-hidden</link>
      <pubDate>Fri, 08 Dec 2017 16:46:55 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/?p=2765</guid>
      <description><![CDATA[How did I miss this?

I love C# and I try to keep up with the latest features. What I didn’t...]]></description>
      <content:encoded><![CDATA[How did I miss this?

I love C# and I try to keep up with the latest features. What I didn’t realize until recently is that the C# 7.1 features are already released. And C# 7.1 includes asynchronous Main methods. Awesome!

By default, new projects in Visual Studio only work with the latest major version of the language (which would be 7.0), but you can change that. So, if you try something like this

<a href="https://msdnshared.blob.core.windows.net/media/2017/12/capture20171208161849214.png"><img width="587" height="113" title="capture20171208161849214" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" alt="capture20171208161849214" src="https://msdnshared.blob.core.windows.net/media/2017/12/capture20171208161849214_thumb.png" border="0" /></a>

you will get this compiler error because Main methods are not allowed to be async (until C# 7.1)
<h4><span style="font-weight: bold">“error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.”</span></h4>
But… open the properties page for your project and click the <strong>Advanced </strong>button on the <strong>Build </strong>tab (you might have to scroll down to see it)

<a href="https://msdnshared.blob.core.windows.net/media/2017/12/capture20171208162336206.png"><img width="686" height="604" title="capture20171208162336206" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" alt="capture20171208162336206" src="https://msdnshared.blob.core.windows.net/media/2017/12/capture20171208162336206_thumb.png" border="0" /></a>

and you’ll see the setting to select which compiler version to use. Change “language version” from “latest major version” to “latest minor version”

<a href="https://msdnshared.blob.core.windows.net/media/2017/12/capture20171208162548723.png"><img width="537" height="326" title="capture20171208162548723" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" alt="capture20171208162548723" src="https://msdnshared.blob.core.windows.net/media/2017/12/capture20171208162548723_thumb.png" border="0" /></a>

If you have Visual Studio 2017 v15.3 or later, you the latest version will be C# 7.1. You will now be able to compile and run code with asynchronous Main methods. Plus you will get all the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/">other goodies that have been added to C# recently</a>.

If you are interested in C# language features, you can track their progress at <a href="https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md">the C# language design repo</a> on GitHub

The sample code above is <a href="https://gist.github.com/negativeeddy/22f5b04e46c9514051a26994788f2434">available as a gist.</a>]]></content:encoded>
    </item>
    <item>
      <title>Setting up Xamarin Live Player</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/setting-up-xamarin-live-player</link>
      <pubDate>Fri, 12 May 2017 15:09:42 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/?p=2696</guid>
      <description><![CDATA[[UPDATE]
You no longer need the preview version of Visual Studio. Updated directions can be found...]]></description>
      <content:encoded><![CDATA[<strong>[UPDATE]</strong>
<blockquote>You no longer need the preview version of Visual Studio. Updated directions can be found in the <span style="text-align: left;color: #333333;line-height: 24px;text-indent: 0px;letter-spacing: normal;font-family: Georgia,'Times New Roman','Bitstream Charter',Times,serif;font-size: 16px;font-style: normal;font-variant: normal;text-decoration: none;cursor: text;float: none;background-color: transparent"> </span><a href="https://developer.xamarin.com/guides/cross-platform/live/install/">Xamarin documentation</a></blockquote>
<strong>[ORIGINAL]</strong>

<a href="https://developer.xamarin.com/guides/cross-platform/live/">Xamarin Live Player</a> is a new tool that allows you to live edit an application running on an Android or iOS device. The interesting bit for many, is that you don’t need a Mac to have this work with your iPhone. The Xamarin Live Player app executes your code for you so that you don’t need to deploy it to the device – you just connect the Xamarin Live Player app to Visual Studio.

The official setup instructions are in the <a href="https://developer.xamarin.com/guides/cross-platform/live/install/">Xamarin documentation</a> but I thought I’d go into a little more detail.

The short version is this
<ol>
 	<li>Install Visual Studio 2017 preview 15.3</li>
 	<li>Install the Xamarin Updater extension</li>
 	<li>Update the Xamarin for Visual Studio extension</li>
 	<li>Install on Xamarin Live Player on your phone</li>
</ol>
The long version:

First install Visual Studio 2017 preview 15.3. The preview can be downloaded at <a href="https://www.visualstudio.com/vs/preview/" title="https://www.visualstudio.com/vs/preview/">https://www.visualstudio.com/vs/preview/</a> I am installing the community edition of the preview, but I already have the released Enterprise Edition on my laptop. That is fine because the previews will install side by side with the release editions of Visual Studio. In addition, it will share components with the release version where it can which will reduce its storage requirements on your hard drive.

At the website, select the Download button, then select the edition of the preview you want to install.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512082746784.png"><img width="773" height="496" title="capture20170512082746784" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512082746784" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512082746784_thumb.png" border="0" /></a>.

The Visual Studio Installer may need to update itself to include the preview options so click update.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512083929462.png"><img width="770" height="431" title="capture20170512083929462" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512083929462" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512083929462_thumb.png" border="0" /></a>

When that is done, ensure you have the Mobile development with .NET selected. In my case I also deselected all the optional items on the right to speed up the install.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512084127114.png"><img width="771" height="432" title="capture20170512084127114" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512084127114" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512084127114_thumb.png" border="0" /></a>

Click install and wait for it to finish.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512084214318.png"><img width="780" height="436" title="capture20170512084214318" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512084214318" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512084214318_thumb.png" border="0" /></a>

When it does, you should have the preview listed alongside any other edition of Visual Studio you already had installed.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085400940.png"><img width="769" height="431" title="capture20170512085400940" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512085400940" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085400940_thumb.png" border="0" /></a>

Now that it is installed you will also see it in the start menu listed as “Visual Studio 2017 Preview (2)”

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085649750.png"><img width="277" height="501" title="capture20170512085649750" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512085649750" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085649750_thumb.png" border="0" /></a>

When you launch it you will be able to tell it is the preview version by the preview flag in the title bar of the window

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085728421.png"><img width="823" height="530" title="capture20170512085728421" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512085728421" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085728421_thumb.png" border="0" /></a>

Open the extension manager (from the menu Tools-&gt;Extensions and Updates) and search for Xamarin in the Online tab. You should see Xamarin Updater among the items. Click the Download button and the close the dialog.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/snip_20170512150456.png"><img width="806" height="559" class="alignnone wp-image-2697" alt="snip_20170512150456" src="https://msdnshared.blob.core.windows.net/media/2017/05/snip_20170512150456.png" /></a>

You may notice it doesn’t install immediately. This extension can’t be installed while Visual Studio is running. Close Visual Studio and the installer will launch.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085837317.png"><img width="478" height="363" title="capture20170512085837317" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512085837317" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085837317_thumb.png" border="0" /></a>

Click Modify and wait for the installer to finish.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085905973.png"><img width="475" height="361" title="capture20170512085905973" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512085905973" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512085905973_thumb.png" border="0" /></a>

Once the installer is finished. Click close and relaunch Visual Studio Preview. Open the Extension Manager again (Tools-&gt;Extensions and Updates) and select the Updates tab. After a moment it should indicate that you have some updates available. Select the “Xamarin for Visual Studio” item and click Update.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512143515227.png"><img width="688" height="477" title="capture20170512143515227" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512143515227" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512143515227_thumb.png" border="0" /></a>

Close the dialog and restart Visual Studio again.

After that updates, Visual Studio is ready to go. Launch it and create a new Xamarin project.

Select File-New Project to launch the project template dialog and select a Xamarin Forms project from the Cross-Platform section. Then click OK

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512090159500.png"><img width="706" height="490" title="capture20170512090159500" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512090159500" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512090159500_thumb.png" border="0" /></a>

In the next dialog select whatever type of app you want, then click OK. For this example, I chose “Blank App”

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512090216208.png"><img width="682" height="377" title="capture20170512090216208" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="capture20170512090216208" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512090216208_thumb.png" border="0" /></a>

When your project finishes loading, select the iOS project as the default project for the solution and you will see an additional option on the debug menu for “Live Player” (you can ignore and cancel any other dialogs that ask you to connect to a Mac for now)

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512091046004.png"><img width="669" height="84" title="capture20170512091046004" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" alt="capture20170512091046004" src="https://msdnshared.blob.core.windows.net/media/2017/05/capture20170512091046004_thumb.png" border="0" /></a>

Click Live Player (or press F5) and the Live Player connection dialog will appear.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/snip_20170512145100.png"><img width="646" height="381" title="snip_20170512145100" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" alt="snip_20170512145100" src="https://msdnshared.blob.core.windows.net/media/2017/05/snip_20170512145100_thumb.png" border="0" /></a>

Now that you have Visual Studio prepared, you need to get the Live Player app from your phone's app store. The Live Player app is necessary to connect to Visual Studio and load your app.

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/20170512_134050000_iOS.png"><img width="266" height="469" title="20170512_134050000_iOS" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" alt="20170512_134050000_iOS" src="https://msdnshared.blob.core.windows.net/media/2017/05/20170512_134050000_iOS_thumb.png" border="0" /></a>

Run the app and it will open like this

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/20170512_141424000_iOS.png"><img width="275" height="486" title="20170512_141424000_iOS" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" alt="20170512_141424000_iOS" src="https://msdnshared.blob.core.windows.net/media/2017/05/20170512_141424000_iOS_thumb.png" border="0" /></a>

Tap “Pair to Visual Studio” and point your phone's camera at the QR code, or type the alphanumeric code into Visual Studio.

Voila! Your app will appear on your phone!

<a href="https://msdnshared.blob.core.windows.net/media/2017/05/20170512_141129000_iOS.png"><img width="283" height="500" title="20170512_141129000_iOS" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" alt="20170512_141129000_iOS" src="https://msdnshared.blob.core.windows.net/media/2017/05/20170512_141129000_iOS_thumb.png" border="0" /></a>

Remember, this just allows you to easily get the app on your phone for testing. If you want to build a deployment package and send it to the store you still need a Mac connected to Visual Studio.

XamarinU also has a free lightning lecture (30 minute video) on setting this up and using it! check it out at <a href="https://university.xamarin.com/lightninglectures/introducing-the-xamarin-live-player">https://university.xamarin.com/lightninglectures/introducing-the-xamarin-live-player </a>]]></content:encoded>
    </item>
    <item>
      <title>An alternative to ConfigureAwait(false) everywhere</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/an-alternative-to-configureawaitfalse-everywhere</link>
      <pubDate>Thu, 09 Feb 2017 15:05:11 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/?p=2355</guid>
      <description><![CDATA[One of the general recommendations you may often read is to use ConfigureAwait(false) in library...]]></description>
      <content:encoded><![CDATA[One of the general recommendations you may often read is to use ConfigureAwait(false) in library code. This is so that when the library is used, it does not block the synchronization context in use by the application (e.g. the UI thread). If the library doesn’t know anything about the app, it doesn’t depend on the application’s context and doesn’t need to run within it. This makes sense but it ends up truly meaning that you have to put ConfigureAwait(false) on every async call in your entire library. To me, that seems ...excessive.

As I see it, If you are using ConfigureAwait(), you probably really care about it and want it to actually work. Unfortunately, because async methods might actually complete synchronously, the call to ConfigureAwait() might not affect anything. That means you have to put it on the next async call too, and so on, until it is on every single method in your library.

Tagging <i>every single call</i> with a decorator method has always bothered me as inelegant and it clutters my code. It’s also something that can easily be forgotten when updating or adding new code. But there is also another more hidden potential issue – <b>the first async call tree</b>. The first time you attempt to await an async method, it doesn’t get the benefit of ConfigureAwait(false). Look at this code

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image0023.png"><img width="447" height="127" title="clip_image002" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image002" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image002_thumb3.png" border="0" /></a>

The first call to FindWorkAsync() has to run <i>before</i> we get a Task to configure. That means that everything that happens inside the first call happens on our caller’s context. That means if any long running actions happen in FindWorkAsync() or in its children, it may affect the callers context.

This behavior can be seen by running <a href="https://github.com/negativeeddy/blog-examples/tree/master/ConfigureAwaitBehavior">this sample WPF application</a>

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image004.png"><img width="306" height="124" title="clip_image004" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image004" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image004_thumb.png" border="0" /></a>

The number on this form is updated by a DispatchTimer every 100ms. DispatchTimers run on the UI thread. If anything blocks the UI thread, you will see that timer pause. In addition, all the buttons are disabled while the work is being done so there is a good visual indicator of when the work is finally finished (the buttons become enabled again).

Using this app, lets look at a couple of scenarios and see how the it behaves...
<h2>Regular async/await</h2>
“<b>Run Case 0</b>” runs a regular set of async/await calls without the use of ConfigureAwait(). This is the basic async/await code as it is usually implemented.

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image006.png"><img width="381" height="133" title="clip_image006" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image006" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image006_thumb.png" border="0" /></a>

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image008.png"><img width="314" height="111" title="clip_image008" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image008" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image008_thumb.png" border="0" /></a>

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image010.png"><img width="362" height="125" title="clip_image010" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image010" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image010_thumb.png" border="0" /></a>

The whole operation takes a few seconds. While this is running, the UI periodically freezes because WorkWithoutCA() calls BlockingWorkAsync() which calls Thread.Sleep(1000). During this sleep time, the timer doesn’t change. The behavior looks like this:
<ol>
 	<li>Buttons disabled</li>
 	<li>UI freezes for 1 second periodically when BlockingWorkAsync() blocks synchronously on Thread.Sleep</li>
 	<li>Buttons enabled</li>
</ol>
<h2>Shallow coverage with ConfigureAwait(false)</h2>
“<b>Run Case 1</b>” runs the same sequence of async/await calls, except that some calls to ConfigureAwait(false) have been added to the entry of the library’s API. The ConfigureAwait(false) calls are only at the top level of our process. The lower level methods DoWorkAsync() and BlockingWorkAsync() are unchanged.

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image012.png"><img width="465" height="133" title="clip_image012" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image012" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image012_thumb.png" border="0" /></a>

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image014.png"><img width="415" height="112" title="clip_image014" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image014" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image014_thumb.png" border="0" /></a>

When this runs, you will notice that the UI freezes for a short time just once. That is the first call to DoWorkAsync() which is still running on the UI thread. The 2nd and 3rd calls to DoWorkAsync() are not on the UI thread and so don’t freeze the UI
<ol>
 	<li>Buttons disabled</li>
 	<li>UI freezes once for 1 second during the first DoWorkAsync() call</li>
 	<li>UI unfrozen for subsequent calls to DoWorkAsync()</li>
 	<li>Buttons enabled</li>
</ol>
It’s this 2nd step that I’m concerned with in this discussion. Obviously the overall behavior is much better because in this case the UI is unfrozen for a majority of the time. But if we are concerned about this at all, why aren’t we concerned about eliminating it completely? I want to push that behavior across <i>all</i> of my library’s functionality, not just stuff that happens after the first await.
<h2>Full coverage with ConfigureAwait(false)</h2>
“<b>Run Case 2</b>” solves this in the way that is typically recommended. You push ConfigureAwait() all the way down the call tree.

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image016.png"><img width="412" height="118" title="clip_image016" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image016" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image016_thumb.png" border="0" /></a>

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image018.png"><img width="422" height="103" title="clip_image018" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image018" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image018_thumb.png" border="0" /></a>

…

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image020.png"><img width="366" height="123" title="clip_image020" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image020" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image020_thumb.png" border="0" /></a>

The behavior is now as we desire it to be – no blocking the UI during any of the calls.
<ol>
 	<li>Buttons disabled</li>
 	<li>UI unfrozen for all calls to DoWorkAsync()</li>
 	<li>Buttons enabled</li>
</ol>
The main problem with this approach is that now we have a maintenance issue. Every new await needs to have ConfigureAwait(false) put on it – just in case. It also tends to clutter the code since this one thing is now <i>everywhere</i>. As a matter of style it makes the code less readable.

So I am proposing an alternative…
<h2>Going manual without ConfigureAwait(false)</h2>
“<b>Run Case 3</b>”

What if we did what ConfigureAwait() does for us, but we do it once at the beginning of our callstack and didn’t have to think about it again? Unfortunately, that means not using a fluent API. The fluent API of ConfigureAwait() is the reason for the “first call” problem. The snippet of code below does not use ConfigureAwait(), but uses a helper object to temporarily remove the SynchronizationContext manually (and restores it before returning to the caller).

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image022.jpg"><img width="252" height="94" title="clip_image022" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image022" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image022_thumb.jpg" border="0" /></a>

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image024.jpg"><img width="302" height="163" title="clip_image024" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image024" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image024_thumb.jpg" border="0" /></a>

<a href="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image026.jpg"><img width="443" height="401" title="clip_image026" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" alt="clip_image026" src="https://msdnshared.blob.core.windows.net/media/2017/02/clip_image026_thumb.jpg" border="0" /></a>

This gives us the same behavior as Case 2 but the code is cleaner. With this technique, I no longer have to remember to put ConfigureAwait(false) all over my code which makes it easier to maintain and to read. The only thing I need to do is insert a single await on the helper object at the beginning of my public APIs and all its children will get called on the default context automatically with no changes to them at all.
<h2>Additional notes</h2>
<ul>
 	<li>The sample is available on <a href="https://github.com/negativeeddy/blog-examples/tree/master/ConfigureAwaitBehavior">my github repo</a>. That code uses some extra methods which I’ve removed in the snippets above. Those methods just print some diagnostic info out so that you can look at the debug output and see the context flowing or not existing at all the various points in the app. It also contains a Case 4 which uses Task.Run to invoke the method instead of the Case 3 wrapper. These two cases are very similar but when Task.Run is used, the method gets queued to the thread pool and will start at some later point in time. Case 3 will initiate the asynchronous method immediately.</li>
 	<li>I am not advocating never using ConfigAwait(false). I’ve had very good success using it in specific targeted scenarios when we knew where the problem was and where to put ConfigureAwait(false) to resolve that problem. I am suggesting that it’s not a cure all and that blanketed use of ConfigAwait is not a good practice.</li>
 	<li>I’m also open to other suggestions. After discussing this with others and looking at a few different options (one of them is in the Github history of case 3), this seems the most reasonable so far.</li>
 	<li>This sample is a WPF application because its easiest to visualize for demo purposes, but the concept is applicable to any .NET library with async code whether running on the client, on a server, or in the cloud.</li>
</ul>
If you have anything to add or suggest, please leave a comment below.]]></content:encoded>
    </item>
    <item>
      <title>Quick dev directory cleanup tip</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/quick-dev-directory-cleanup-tip</link>
      <pubDate>Wed, 21 Sep 2016 11:48:54 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/?p=1895</guid>
      <description><![CDATA[When cleaning up drive space, the first thing I do is remove the ‘obj’, ‘bin’, and ‘packages’...]]></description>
      <content:encoded><![CDATA[When cleaning up drive space, the first thing I do is remove the ‘obj’, ‘bin’, and ‘packages’ directories from my development directories. They are temporary and will be rebuilt the next time I build the related project. Because I end up with a lot of little test &amp; sample projects that I don’t refer to often, their binaries and nuget directories are just taking up space.

The reason this is better than doing a Clean Solution is that Clean Solution only removes the outputs of the build. It doesn't remove the nuget packages which in my case were a significant percentage of my overall dev directory space.
<h3>The old way</h3>
I used to do this with a little Windows Explorer trick – search filters. It looks like this

<a href="https://msdnshared.blob.core.windows.net/media/2016/09/capture20160921110426561.png"><img width="759" height="303" title="capture20160921110426561" style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" alt="capture20160921110426561" src="https://msdnshared.blob.core.windows.net/media/2016/09/capture20160921110426561_thumb.png" border="0" /></a>

“type:folder name:obj” tells explorer to find all the items that have “obj” in the name and are folders. Then I can easily “Select All” and delete. Then repeat for Bin and for Packages. (There is one caveat here that the name search is a substring search, so it will also return directories named “object” too.)
<h3>The PowerShell way</h3>
But today I got to thinking. I wanted to do that in one step. So here is a PowerShell command that will iterate from the current directory and find all child directories named ‘obj’, ‘bin’, or ‘packages’ and prompt me to delete them.
<blockquote><span style="font-family: Courier New">get-childitem -Directory -Recurse | where-object {$_.Name -eq 'bin' -or $_.Name -eq 'obj' -or $_.Name -eq 'packages'} | Remove-Item –Force –Recurse</span></blockquote>
I put this in <a target="_blank" href="https://gist.github.com/negativeeddy/5b41c297e38f0cb82415482a4475a29b">a file named clean-devfolder.ps1</a><em><strong></strong></em> and it works like a champ.

If, instead, you want to see a preview of which directories will be removed, you can add -WhatIf to the end of the whole command.]]></content:encoded>
    </item>
    <item>
      <title>Asynchronous infinite loops instead of timers</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/asynchronous-infinite-loops-instead-of-timers</link>
      <pubDate>Thu, 30 Jun 2016 10:12:27 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/?p=1845</guid>
      <description><![CDATA[Did it occur to you that an infinite loop, with async/await inside it, isn't really an infinite...]]></description>
      <content:encoded><![CDATA[Did it occur to you that an infinite loop, with async/await inside it, isn't really an infinite loop? It looks like one (which is usually bad) but because of the asynchrony, we know that it isn't executing the entire method at one time. Part executes now, then sometime later it periodically resumes – that sounds kind of like a timer!

Let’s say I have some UI work I need to do on a periodic basis. Normally I have two options
<ol>
	<li><a href="https://msdn.microsoft.com/en-us/library/hh195051(v=vs.110).aspx" target="_blank">Spin up a new Task </a>which has a loop which does a bit of work, updates the UI, then sleeps for a period of time.</li>
	<li>Create a <a href="https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer(v=vs.110).aspx" target="_blank">DispatchTimer</a>, configure it properly<a href="https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer(v=vs.110).aspx" target="_blank"> </a>and do the work in the Tick event</li>
</ol>
The first option gives us code with clear intent (“loop and update forever!”), but it introduces multiple delegates, potential multithreading complexities depending on the work being done and we still have to get back onto the UI thread to update the UI.
<pre>void DoWorkPollingTask()
{
    Task.Run(async () =&gt;
    {
        while (true)
        {
            // do the work in the loop
            string newData = DateTime.Now.ToLongTimeString();

            // update the UI on the UI thread
            Dispatcher.Invoke(() =&gt; txtTicks.Text = "TASK - " + newData);

            // don't run again for at least 200 milliseconds
            await Task.Delay(200);
        }
    });
}
</pre>
whereas the second option, while keeping us on a single thread (the UI thread) spreads our intent across multiple methods because the "repeat" behavior is separate from the "work" behavior (i.e. the only way we know this is a periodic activity is that the method is named _timer_Tick) and may make for more difficult maintenance if it gets more complicated.
<pre>DispatcherTimer _timer = new DispatcherTimer();

void DoWorkTimer()
{
    _timer.Interval = TimeSpan.FromMilliseconds(200);
    _timer.Tick += _timer_Tick;
    _timer.IsEnabled = true;
}

void _timer_Tick(object sender, EventArgs e)
{
    // do the work in the loop
    string newData = DateTime.Now.ToLongTimeString();

    // update the UI on the UI thread
    txtTicks.Text = "TIMER - " + newData;
}
</pre>
There is a third option. Use an asynchronous loop. Even though this looks like an infinite loop, its really not. Because of the await of the delay Task, this method yields control back to the its caller periodically. If this weren’t an async method with a valid asynchronous operation, it would be a synchronous method and would deadlock the UI when we called it.

But since it is not, it works as needed and gives us both a very clear intent of what the code is supposed to do as well as keeps us on the UI thread the whole time (the magic of await!) so we don't have multithreaded issues or multiple delegates/callbacks.
<pre>private async Task DoWorkAsyncInfiniteLoop()
{
    while (true)
    {
        // do the work in the loop
        string newData = DateTime.Now.ToLongTimeString();

        // update the UI
        txtTicks.Text = "ASYNC LOOP - " + newData;

        // don't run again for at least 200 milliseconds
        await Task.Delay(200);
    }
}
</pre>
The real trick to making this work though, is not in the DoWorkAsyncInfiniteLoop method. Its how we call it. You do not await the call to it.
<pre>private void bttnStart_Click(object sender, RoutedEventArgs e)
{
    // invoke loop method but DO NOT await it
    DoWorkAsyncInfiniteLoop();
}</pre>
This will start the async loop but we do not want our code to await here for it to finish (because it won’t). We treat it as “fire and forget.”

This will also cause a green squiggle in Visual Studio because “Hey you forget to await this obviously async method!!!” We can ignore that, or just stash the returned task into a local variable so it doesn’t complain. What I <strong>will not</strong> do to “fix” the green squiggle is make the looping method return void instead of Task. Always return a Task, you never know who might want it in the future (maybe a future change also introduces a cancellation feature).

Other thoughts:
<ul>
	<li>Should I write code this way? As always, it depends. But having one more option doesn't hurt.</li>
	<li>Of course these don’t have to be infinite loops, we could institute some kind of flag or cancellation mechanism, but this way makes for simpler example code and a more interesting blog title!</li>
	<li>Don’t do this if you have a large amount of work to do. This is all happening on the UI thread so each time around the loop, its grabbing that UI thread and using it (which means the UI is not responsive at that time). If the work is significant, then Task.Run is a probably better option to offload the work onto another thread.</li>
	<li>The simple example here doesn't prevent reentrancy. If something calls the method again, you will get a second  loop running in addition to the original loop. It won't be parallel (still only on the UI thread) but will be <a href="https://blogs.msdn.microsoft.com/benwilli/2015/09/10/tasks-are-still-not-threads-and-async-is-not-parallel/" target="_blank"> interleaved with the rest of the UI thread work</a>.</li>
</ul>
The above sample source is available on my <a href="https://github.com/negativeeddy/blog-examples/tree/master/AsyncInfiniteLoops">GitHub</a>.]]></content:encoded>
    </item>
    <item>
      <title>Waaaaay oversimplified async/await plumbing</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/waaaaay-oversimplified-asyncawait-plumbing</link>
      <pubDate>Mon, 28 Mar 2016 09:46:19 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/?p=1841</guid>
      <description><![CDATA[Often, when someone asks "how does this async await stuff actually work"? There is a lot of hand...]]></description>
      <content:encoded><![CDATA[Often, when someone asks "how does this async await stuff actually work"? There is a lot of hand waving or someone says "just use reflection and look at it" but the real compiled code is a complex recursive state machine. So I want to show a (relatively) simplified example that isn’t the real thing but is conceptually correct.

Conceptually, the way I think about it is that the compiler just breaks down my method into a series of tasks that need to be run. Lets start with a simple scenario which has a single await.

<a href="https://msdnshared.blob.core.windows.net/media/2016/03/image678.png"><img style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" title="image" src="https://msdnshared.blob.core.windows.net/media/2016/03/image_thumb524.png" alt="image" width="473" height="251" border="0" /></a>

We kind of hide the Task by default but if you change it to look like this, you can see we aren't awaiting the method, we are awaiting the Task returned from the method.

<a href="https://msdnshared.blob.core.windows.net/media/2016/03/image679.png"><img style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" title="image" src="https://msdnshared.blob.core.windows.net/media/2016/03/image_thumb525.png" alt="image" width="473" height="251" border="0" /></a>

Now we can take the async/await keywords away by breaking the method up into 2 areas – the code that runs before the await, and the code that runs after the await. Because the GetCountAsync() call is async, we can’t run that “after” code immediately. We want to wait until after countTask is complete and then run the “after” code. So what actually runs looks more like this

<a href="https://msdnshared.blob.core.windows.net/media/2016/03/image680.png"><img style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" title="image" src="https://msdnshared.blob.core.windows.net/media/2016/03/image_thumb526.png" alt="image" width="467" height="362" border="0" /></a>

As you can see, we have taken the “after” code and told it to run as a continuation of the countTask. This means that the GetCountAsync method will run and <em>whenever</em> it gets done, the “after” code will execute. Of course this means we have another task to deal with. The “after” code continuation provides us a new Task object to know when that is done. When that is finished we know that our entire method is finished. So we can return that final Task to the caller of our method so that they will know when we are complete.

Now <strong><em>this is definitely not a complete picture</em></strong> (e.g. we are not dealing with looping or exceptions or managing the UI thread). But I find this a pretty compelling way to demonstrate a couple of key principles.
<ol>
	<li>When you use the async keyword, your method becomes asynchronous because it gets broken into Tasks based on the await keywords in use.</li>
	<li>Your async method will return before it completes. Yes, that's the whole point and is obvious to some people, but here it is shown explicitly because in the final example above, our method isn’t doing any real work except creating the Task chain and then returning.</li>
	<li>The code before the first await always runs synchronously. There is no Task management going on until you hit the first await. So if you have a 10 second operation before the first await, the method will take 10 seconds and then hook up the task chain and return.</li>
	<li>This is why your callstack looks different when debugging. The “after” code is not being called from DoWorkWithoutAwait(). It is being called directly from the .NET Task infrastructure as a continuation of the previous task.</li>
</ol>
<h3>Taking that a bit further</h3>
Lets take that concept and apply it to a more realistic method which contains  multiple awaits.

<a href="https://msdnshared.blob.core.windows.net/media/2016/03/image681.png"><img style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" title="image" src="https://msdnshared.blob.core.windows.net/media/2016/03/image_thumb527.png" alt="image" width="472" height="460" border="0" /></a>

In the same steps, we can think of this as dividing our method up into a number of intermediate Tasks separated by the await keywords.

<a href="https://msdnshared.blob.core.windows.net/media/2016/03/image682.png"><img style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border-width: 0px" title="image" src="https://msdnshared.blob.core.windows.net/media/2016/03/image_thumb528.png" alt="image" width="696" height="763" border="0" /></a>

Again, this just demonstrates those same points that I see some developers forget or struggle with. When I see a series of await keywords, I’m thinking about how that method gets broken down into individual tasks – not how it is going to run as a single unit. This helps me remember that even if this ends up running on a single thread, the fact that is gets chunked up means that other scheduled code can potentially run in between my method’s various sections. You can also see this concept graphically in this <a href="https://blogs.msdn.microsoft.com/benwilli/2015/09/10/tasks-are-still-not-threads-and-async-is-not-parallel/" target="_blank">previous post</a>.

&nbsp;

Additional files
<ul>
	<li><a href="https://doc.co/PVk1BY" target="_blank">PPT showing code transitions</a></li>
	<li><a title="Source code" href="https://github.com/negativeeddy/blog-examples/tree/master/AsyncConceptualSimplification" target="_blank">Source code</a></li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Windows Live Writer lives on as Open Live Writer!</title>
      <link>https://docs.microsoft.com/archive/blogs/benwilli/windows-live-writer-lives-on-as-open-live-writer</link>
      <pubDate>Fri, 11 Dec 2015 07:50:00 GMT</pubDate>
      <dc:creator><![CDATA[BenWilli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/benwilli/2015/12/11/windows-live-writer-lives-on-as-open-live-writer/</guid>
      <description><![CDATA[I am happy to be posting this blog entry from the newly announced Open Live Writer! The most...]]></description>
      <content:encoded><![CDATA[<p>I am happy to be posting this blog entry from the newly announced Open Live Writer! The most excellent blogging tool has not been actively developed for some time. But efforts have been made and now a fork of that well loved application is now provided as the open source project Open Live Writer under the MIT license.</p>
<p>You can get the latest version at their home page <a title="https://openlivewriter.org/" href="https://openlivewriter.org/">https://openlivewriter.org/</a> and if you want to get involved with helping continue to make it better check out the source at <a title="https://github.com/OpenLiveWriter" href="https://github.com/OpenLiveWriter">https://github.com/OpenLiveWriter</a>.</p>
<p>Looking through my email archives, I made an internal suggestion to open source this back in April of 2014. I have no idea if that started the actual process because I wasn't involved, but if it did,&nbsp; your welcome <img class="wlEmoticon wlEmoticon-smile" style="border-style: none;" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/01/78/metablogapi/4744.wlEmoticon-smile_3187E60D.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-01-78-metablogapi/4744.wlEmoticon_2D00_smile_5F00_3187E60D.png" alt="Smile" /></p>]]></content:encoded>
    </item>
  </channel>
</rss>