简体   繁体   English

Async Await Method将在等待点阻止UI

[英]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. 对于我的GridView数据源,我有一个繁重的数据库事务,我把它放在await部分。 But at this point, the UI will block and I do not know the reason. 但在这一点上,UI将阻止,我不知道原因。 Where is the problem? 问题出在哪儿?

You LINQ query should be async. 你LINQ查询应该是异步的。 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(); 我刚刚通过添加.ToList();解决了我的问题.ToList(); at the end of my LINQ query: 在我的LINQ查询结束时:

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. 但我现在还不知道为什么它在没有阻止UI的情况下正常运行。 Is there related to lazy loading or what? 是否与延迟加载或什么相关?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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