我正在尝试在单独的线程中加载数据库上下文。然后在完成后更新表单的显示。
有没有人可以告诉我正确的做法。
目前我的上下文已加载,但我的_context似乎没有返回Context:
public static ProjectEntities Context = new ProjectEntities();
public static void LoadAsync(ref ProjectEntities _context, Type _table)
{
LoadAsyncImpl(_table);
_context = Context;
}
private static async void LoadAsyncImpl(Type _table)
{
ProjectEntities _context = new ProjectEntities();
await _context.Set(_table).LoadAsync();
Context = _context;
}
}
答案 0 :(得分:0)
假设你正在使用WinForms,你可能会尝试这样的事情。请注意,_context
不再是静态的。
private ProjectEntities _context;
public MainForm()
{
InitializeComponent();
}
private async void MainForm_Loaded(object sender, EventArgs e)
{
await LoadAsync()
.ContinueWith(x => {
if (!x.IsFaulted)
{
_context = x.Result;
Text = "Loaded";
/* any other stuff on the main UI thread after loading */
}
else
{
/* and don't forget that sometimes things fail */
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
private async Task<ProjectEntities> LoadAsync()
{
var context = new ProjectEntities();
await context.Set(...).LoadAsync();
return context;
}