Reputation: 129
for using async/await in entityframeworkcore i use this way, I want to know if my method is correct or not? Is there a better way?
public async Task<T> Create(T entity)
{
using (var db = new myDbContext())
{
var created = await db.Set<T>().AddAsync(entity);
await db.SaveChangesAsync();
return created.Entity;
}
}
public async Task<IEnumerable<T>> GetAll()
{
using (var db = new myDbContext())
{
var items = await db.Set<T>().ToListAsync();
return items;
}
}
and for using this method:
IDataService<Stock> Data = new GenericDataService<Stock>();
Data.Create(new Stock { id = 2, name = "ok" }).Wait();
foreach (var item in Data.GetAll().Result)
{
MessageBox.Show(item.name);
}
Upvotes: 2
Views: 3369
Reputation: 4824
Avoid sync-over-async .Result
for not completed Task
because it's nonsense in Asynchronous programming. It may cause deadlocks and makes the nature of async
useless.
In case of synchronous caller method you may at least do this
IProgress<string> status = new Progress<string>(s => MessageBox.Show(s));
Task.Run(async () =>
{
Stock entity = await Data.Create(new Stock { id = 2, name = "ok" });
foreach (var item in await Data.GetAll())
{
status.Report(item.name);
}
});
Progress
here just executes callback in the UI thread. Avoid updating UI from pooled threads.
But it's not the only way to solve it.
If you're in Event handler, just make it async
and simply use await
inline without Task.Run()
and callback.
Also I suggest to rename the methods to CreateAsync
and GetAllAsync
.
Upvotes: 3