Click here to Skip to main content
14,366,152 members
Rate this:
Please Sign up or sign in to vote.
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:

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 16:19pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

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();
        }
    }
}
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100