Click here to Skip to main content
15,888,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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.
Posted
Updated 27-Nov-16 15:19pm

1 solution

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:
C#
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();
        }
    }
}
 
Share this answer
 
v2
Comments
SrikantSahu 28-Nov-16 1:59am    
Thanks Dave, this is working. You are right, there is no point in spawning a thread here, but I just wanted to try out the async with raw sql query. Just wanted to let you know that, putting an await before LoadDataAsync() and marking the page_load as async in my original solution also worked.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900