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!
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With