我有一个winform
并列有六个listbox
。每个listbox
下都有textbox
和Button
标记为"添加。"当您在textbox
中添加内容并按下添加按钮后,使用EF,我会更新listbox
的表格,然后重新dataBind
listbox
。这是“添加”按钮的一个事件处理程序的示例:
private void btnOfferType_Click(object sender, EventArgs e)
{
TypeCategoryAdd("OfferType", tbOfferType.Text.Trim());
}
TypeCategoryAdd
功能如下所示。我想这样做(注意await
):
private async void btnOfferType_Click(object sender, EventArgs e)
{
await TypeCategoryAdd("OfferType", tbOfferType.Text.Trim());
}
我需要做些什么才能让TypeCategoryAdd
函数在不同的上下文中运行,以便在发生数据库更新时winform
用户界面不会冻结?
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;
}
答案 0 :(得分:1)
您应该如何利用EF 6中的async
方法:
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;
}
}
}
答案 1 :(得分:1)
您可以将数据库访问权限包含在Task
和await
上。
private async void btnOfferType_Click(object sender, EventArgs e)
{
await Task.Run(()=>TypeCategoryAdd("OfferType", tbOfferType.Text.Trim()));
}