Winform-将方法更改为异步/等待 [英] Winform - changing a method to async/await
问题描述
我有一个winform
和六个listbox
并排.在每个listbox
下都有一个textbox
和一个标记为添加"的Button
.当您使用EF将某些内容放入textbox
并按添加"按钮时,我将更新该listbox
的表,然后重新dataBind
listbox
.这是添加"按钮的事件处理程序之一的示例:
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
功能在下面列出.我想这样做(注意await
):
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());
}
要使TypeCategoryAdd
函数在不同的上下文中运行,以便在更新数据库时不会冻结winform
UI,我需要做什么?
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;
}
推荐答案
利用EF 6中的async
方法应该做什么:
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;
}
}
}
这篇关于Winform-将方法更改为异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!