In the article “Async and Await” by Stephen Cleary it is said that to run awaitable on the thread pool you need to call ConfigureAwait(false) on that awaitable. That somehow does not match my experience. I have created a little app that I think proves that it is not necessary to call ConfigureAwait to execute awaitable on a separate thread.
I have used log4net tool for logging purpose. Without using a ‘ConfigureAwait’ method the awaitable executes on a different thread ([3]) then the UI ToolStripButton1_Click call(UI thread is [1] and pool thread is [3] – code and log output is attached below).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public Form1()
{
InitializeComponent();
}
private async void ToolStripButton1_Click(object sender, EventArgs e)
{
await TestAsync();
}
private async Task TestAsync()
{
log.Info("Button clicked before Run Sleep task. Expect to run this from UI thread");
Task t = Task.Run( () =>
{
log.Info("Button clicked from Run before Sleep. Expect to run this from a pool thread");
Thread.Sleep(1000 * 5);
log.Info("Button clicked from Run after Sleep. Expect to run this from a pool thread");
return true;
});//.ConfigureAwait(continueOnCapturedContext: false);
await t;
log.Info("Button clicked after Run. Expect to run this from UI thread"); // Expect to run this in UI thread
}
}
}
Log output looks like this:
2020-01-31 19:57:14,805 [1] INFO WindowsFormsApp1.Form1[MoveNext] - Button clicked before Run Sleep task. Expect to run this from UI thread
2020-01-31 19:57:14,835 [3] INFO WindowsFormsApp1.Form1[b__3_0] - Button clicked from Run before Sleep. Expect to run this from a pool thread
2020-01-31 19:57:19,837 [3] INFO WindowsFormsApp1.Form1[b__3_0] - Button clicked from Run after Sleep. Expect to run this from a pool thread
2020-01-31 19:57:19,839 [1] INFO WindowsFormsApp1.Form1[MoveNext] - Button clicked after Run. Expect to run this from UI thread
I did not call ConfigureAwait(false) and awaitable is executed on the thread pool.