如何在EF 6.0中调用异步查询 [英] How to call async query in EF 6.0

查看:184
本文介绍了如何在EF 6.0中调用异步查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用EF 6.0原始Sql查询与Async绑定gridview,但系统继续进行无休止的执行和task.Result永远不会填充。



我尝试了什么:



  protected   void  Page_Load( object  sender,EventArgs e)
{
var task = LoadDataAsync();
task.Wait();
var data = task.Result;
GridView1.DataSource = data;
GridView1.DataBind();
}

私有 async 任务< list< user>> ; LoadDataAsync()
{
List< user> users = null ;
使用 var context = new BlogEntities())
{
users = await context.Users.SqlQuery( 从[用户]中选择*。ToListAsync();
}

返回用户;

}



任何人都可以告诉我,如何调用异步方法并成功绑定数据。

解决方案

您的代码基本上是单线程的。你有2个线程,但是一个完全被阻塞在另一个上。在任何情况下,将LoadData代码放在后台线程上,因为它是您唯一要做的事情,与您完全跳过所有Task / async / await东西没有什么不同。通过线程化你没有获得任何性能上的好处。



但是,对于简单的事情,你可以这样试试:

 受保护  async   void  Page_Load( object  sender,EventArgs e)
{
if (!IsPostBack())
{
var result = await LoadDataAsync() ;
GridView1.DataSource = result;
GridView1.DataBind();
}
}

受保护任务< list< user>> LoadDataAsync()
{
return Task.Factory.StartNew< list< user>>(()= >
{
使用 var context = new BlogEntities())
{
users = context.Users.SqlQuery( SELECT * FROM [User])。ToList();
}
}
}


I am trying to bind a gridview using EF 6.0 raw Sql query with Async, but the system goes on for endless execution and task.Result is never populated.

What I have tried:

protected void Page_Load(object sender, EventArgs e)
    {
        var task = LoadDataAsync();
        task.Wait();
        var data = task.Result;
        GridView1.DataSource = data;
        GridView1.DataBind();
    }

private async Task<list<user>> LoadDataAsync()
    {
        List<user> users = null;
        using (var context = new BlogEntities())
        {
            users = await context.Users.SqlQuery("Select * from [User]").ToListAsync();
        }

        return users;

    }


Can anyone please let me know, how to call the async method and get the data bind successfully.

解决方案

Your code is essentially single threaded. You've got 2 threads, but one is completely blocked waiting on the other. In any case, putting the LoadData code on a background thread, since it's the only thing you're doing, is no different than if you completely skipped all the Task/async/await stuff. You're not getting any performance benefit by threading this.

But, to simply things a bit, you can try it this way:

protected async void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack())
    {
        var result = await LoadDataAsync();
        GridView1.DataSource = result;
        GridView1.DataBind();
    }
}

protected Task<list<user>> LoadDataAsync()
{
    return Task.Factory.StartNew<list<user>>(() =>
    {
        using (var context = new BlogEntities())
        {
            users = context.Users.SqlQuery("SELECT * FROM [User]").ToList();
        }
    }
}


这篇关于如何在EF 6.0中调用异步查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆