Reputation: 4601
class Laziness
{
static string cmdText = null;
static SqlConnection conn = null;
Lazy<Task<Person>> person =
new Lazy<Task<Person>>(async () =>
{
using (var cmd = new SqlCommand(cmdText, conn))
using (var reader = await cmd.ExecuteReaderAsync())
{
if (await reader.ReadAsync())
{
string firstName = reader["first_name"].ToString();
string lastName = reader["last_name"].ToString();
return new Person(firstName, lastName);
}
}
throw new Exception("Failed to fetch Person");
});
public async Task<Person> FetchPerson()
{
return await person.Value;
}
}
And the book, "Concurrency in .NET" by Riccardo Terrell, June 2018, says:
But there's a subtle risk. Because Lambda expression is asynchronous, it can be executed on any thread that calls Value and the expression will run within the context. A better solution is to wrap the expression in an underlying Task which will force the asynchronous execution on a thread pool thread.
I don't see what's the risk from the current code ?
Is it to prevent deadlock in case the code is run on the UI thread and is explicity waited like that:
new Laziness().FetchPerson().Wait();
Upvotes: 16
Views: 20971
Reputation: 43474
I simplified your example to show what happens in each case. In the first case the Task
is created using an async
lambda:
Lazy<Task<string>> myLazy = new(async () =>
{
string result = $"Before Delay: #{Thread.CurrentThread.ManagedThreadId}";
await Task.Delay(100);
return result += $", After Delay: #{Thread.CurrentThread.ManagedThreadId}";
});
private async void Button1_Click(object sender, EventArgs e)
{
int t1 = Thread.CurrentThread.ManagedThreadId;
string result = await myLazy.Value;
int t2 = Thread.CurrentThread.ManagedThreadId;
MessageBox.Show($"Before await: #{t1}, {result}, After await: #{t2}");
}
I embedded this code in a new Windows Forms application with a single button, and on clicking the button this message popped up:
Before await: #1, Before Delay: #1, After Delay: #1, After await: #1
Then I changed the valueFactory
argument to use Task.Run
instead:
Lazy<Task<string>> myLazy = new(() => Task.Run(async () =>
{
string result = $"Before Delay: #{Thread.CurrentThread.ManagedThreadId}";
await Task.Delay(100);
return result += $", After Delay: #{Thread.CurrentThread.ManagedThreadId}";
}));
Now the message is this:
Before await: #1, Before Delay: #3, After Delay: #4, After await: #1
So not using Task.Run
means that your code before, between and after the await
s will run on the UI thread. Which might not be a big deal, unless there is CPU intensive or I/O blocking code hidden somewhere. For example the constructor of the Person
class, as innocent as it might look, could contain some call to a database or web API. By using Task.Run
you can be sure that the initialization of the Lazy
class will not touch the UI thread before it's done.
Upvotes: 12
Reputation: 456437
I don't see what's the risk from the current code ?
To me, the primary issue is that the asynchronous initialization delegate doesn't know what context/thread it'll run on, and that the context/thread could be different based on a race condition. For example, if a UI thread and a thread pool thread both attempt to access Value
at the same time, in some executions the delegate will be run in a UI context and in others it will be run in a thread pool context. In the ASP.NET (pre-Core) world, it can get a bit trickier: it's possible for the delegate to capture a request context for a request that is then canceled (and disposed), and attempt to resume on that context, which isn't pretty.
Most of the time, it wouldn't matter. But there are these cases where Bad Things can happen. Introducing a Task.Run
just removes this uncertainty: the delegate will always run without a context on a thread pool thread.
Upvotes: 12