Inside Man
Inside Man

Reputation: 4372

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?

Upvotes: 3

Views: 214

Answers (2)

the_joric
the_joric

Reputation: 12226

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

Upvotes: 3

Inside Man
Inside Man

Reputation: 4372

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?

Upvotes: 2

Related Questions