Lazy<Task<T>> with asynchronous initialization

限于喜欢 提交于 2021-02-04 19:40:30

问题


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 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();

回答1:


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.




回答2:


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 Lazy<Task<string>>(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;
    var 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 Lazy<Task<string>>(() => 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 awaits will run in the UI thread. Which may not be a big deal unless there is CPU intensive or IO blocking code hidden somewhere. For example the constructor of the Person class, as innocent as may seem, could contain some call to a 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.



来源:https://stackoverflow.com/questions/57517656/lazytaskt-with-asynchronous-initialization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!