The Task.Yield
method "creates an awaitable task that asynchronously yields back to the current context when awaited." I am searching for something similar that should guarantee that any code that follows will run on a ThreadPool
thread. I know that I could achieve this be enclosing all the following code in a Task.Run
, but I am searching for an inline solution that doesn't create an inner scope.
private async void Button1_Click(object sender, EventArgs e)
{
await Task.Yield(); // Doesn't do what I want
// Code that should run on the ThreadPool
}
private async void Button1_Click(object sender, EventArgs e)
{
// Does what I want, but I am not happy with the added indentation and scope
await Task.Run(() =>
{
// Code that should run on the ThreadPool
});
}
The best I can think of is to use the Task.Run
with an empty delegate, and configure the awaiting to not capture the synchronization context:
private async void Button1_Click(object sender, EventArgs e)
{
// Probably does what I want, but it looks ugly
await Task.Run(() => { }).ConfigureAwait(continueOnCapturedContext: false);
// Code that should run on the ThreadPool
}
This looks like an obscure line of code, and I am not sure that expresses well enough the intent of being there. I am also not sure if it provides the guarantees I want. Is there any other solution?
Btw this question is inspired by a Marc Gravell's answer to a related question.
Update: I should give a more specific reason about why using the standard await Task.Run(() =>
is not ideal in my case. I have some code that should run on the ThreadPool
or not, depending on some condition. So a Task.Yield
equivalent would allow me to do this:
private bool _executeOnThreadPool;
private async void Button1_Click(object sender, EventArgs e)
{
if (_executeOnThreadPool) await SwitchToTheThreadPool();
// Code that should run on the ThreadPool or the UI thread
}
I can't do the same thing with Task.Run
without code duplication, or without adding lambdas and indirection.