问题
I have a winform
with six listbox
side-by-side. Under each listbox
there is a textbox
and a Button
labeled "Add." When you put something in the textbox
and press the Add button, using EF, I update a table for that listbox
and I re-dataBind
the listbox
. Here's a sample of one of the event handlers for Add button:
private void btnOfferType_Click(object sender, EventArgs e)
{
TypeCategoryAdd("OfferType", tbOfferType.Text.Trim());
}
TypeCategoryAdd
function is listed below. I want to do this (notice the await
):
private async void btnOfferType_Click(object sender, EventArgs e)
{
await TypeCategoryAdd("OfferType", tbOfferType.Text.Trim());
}
What do I need to do in order make the TypeCategoryAdd
function to run on different context so that the winform
UI don't freeze up when DB update is happening?
private void TypeCategoryAdd (string table, string item)
{
if (string.IsNullOrEmpty(item)) return;
using (MenuGenerator.NewArchMenuGeneratorEntities con = new NewArchMenuGeneratorEntities())
{
switch (table)
{
case "OfferType":
if (con.OfferTypes.Any(x=>x.Name == item))
{
MessageBox.Show("There is already a " + item + " on the list!");
tbOfferType.Text = "";
return;
}
OfferType ot = new OfferType();
ot.Name = item;
con.OfferTypes.Add(ot);
try
{
con.SaveChanges();
tbOfferType.Text = "";
lstOfferType.DataSource = con.OfferTypes.OrderBy(x=>x.Id).ToList();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex.ToString());
}
break;
}
return;
}
回答1:
What you should do it to take advantage of the async
methods in EF 6:
private async Task TypeCategoryAdd (string table, string item)
{
if (string.IsNullOrEmpty(item)) return;
using (MenuGenerator.NewArchMenuGeneratorEntities con = new NewArchMenuGeneratorEntities())
{
switch (table)
{
case "OfferType":
if (await con.OfferTypes.AnyAsync(x=>x.Name == item))
{
MessageBox.Show("There is already a " + item + " on the list!");
tbOfferType.Text = "";
return;
}
OfferType ot = new OfferType();
ot.Name = item;
con.OfferTypes.Add(ot);
try
{
await con.SaveChangesAsync();
tbOfferType.Text = "";
lstOfferType.DataSource = await con.OfferTypes.OrderBy(x=>x.Id).ToListAsync();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex.ToString());
}
break;
}
return;
}
}
}
回答2:
You can wrap your database access in a Task
, and await
on that.
private async void btnOfferType_Click(object sender, EventArgs e)
{
await Task.Run(()=>TypeCategoryAdd("OfferType", tbOfferType.Text.Trim()));
}
来源:https://stackoverflow.com/questions/37402108/winform-changing-a-method-to-async-await