Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async Await Issue for methods with parameters

Tags:

c#

I'm kinda new to Async Await concept. Have the following method in a Repository

    public TEntity Get(int id)
    {
        return Context.Set<TEntity>().Find(id);
    }

I call this method from another method

 BindingSource.DataSource = unitOfWork.ClientDemos.Get(newClient.ClientId);

I want to Async this as this could take a while depending on sever speed and such. How do I actually do this? Every way I tired gave me differnt types of errors. I don't want to bother you all with my wrong approaches. But here is something I tried and did not work.

Task <IEnumerable<ClientDemographic>> tsk= new Task <IEnumerable<ClientDemographic> >(unitOfWork.ClientDemos.Get(newClient.ClientId));
                tsk.Start();
                BindingSource.DataSource = await tsk;

It works wonders when there are no parameters to pass and the returning type is int. Like the following. This one works well.

 Task<int> tsk = new Task<int>(unitOfWork.Complete);
                tsk.Start();
                rej = await tsk;

Please shed some light to this matter. I really appreciate it! Cheers! Thanks!

like image 668
Randika Wijekoon Avatar asked Jan 29 '23 20:01

Randika Wijekoon


2 Answers

Use Task.Run

BindingSource.DataSource = await Task.Run(() => unitOfWork.ClientDemos.Get(newClient.ClientId));

You should also read up on Async/Await - Best Practices in Asynchronous Programming

like image 143
Nkosi Avatar answered Feb 02 '23 10:02

Nkosi


It looks like you are probably using EntityFramework, if so, there is a FindAsync method. If that's the case, it will be better to use that than Task.Run.

public async Task<TEntity> GetAsync(int id)
{
    return await Context.Set<TEntity>().FindAsync(id);
}

Then:

BindingSource.DataSource = await unitOfWork.ClientDemos.GetAsync(newClient.ClientId);
like image 27
Dave M Avatar answered Feb 02 '23 10:02

Dave M