简体   繁体   中英

Async Await Method will block UI at await point

Here is my button event:

private async void btnTarget_Click(object sender, EventArgs e)
{
    using (DataBaseDataContext db = new DataBaseDataContext())
    {
        targtGirdView.DataSource = await Task.Run(() =>
        {
            return heavyLinqToSQLQuery;
        });
    }
}

for my GridView datasource, I have a heavy database transaction which I put it in an await section. But at this point, the UI will block and I do not know the reason. Where is the problem?

You LINQ query should be async. And code should look something like

private async void btnTarget_Click(object sender, EventArgs e)
{
    using (DataBaseDataContext db = new DataBaseDataContext())
    {
        targtGirdView.DataSource = await heavyLinqToSQLQuery.ToListAsync();
    }
}

I just solved my problem by adding .ToList(); at the end of my LINQ query:

private async void btnTarget_Click(object sender, EventArgs e)
{
    using (DataBaseDataContext db = new DataBaseDataContext())
    {
        targtGirdView.DataSource = await Task.Run(() =>
        {
            return heavyLinqToSQLQuery.ToList();
        });
    }
}

But I have no idea why it is running correctly without blocking UI now. Is there related to lazy loading or what?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM