我正在尝试从 MongoDB 集合中检索数据,但是发生了一些奇怪的事情。如果我显示 MessageBox,则数据获取有效,如果不显示,则数据获取无效。
static class MongoDBController {
static MongoClient client = new MongoClient("mongodb://localhost");
public static async Task<List<Course>> GetCourses(string dbName = "school") {
// Get our course collection
var db = client.GetDatabase(dbName);
var collection = db.GetCollection<Course>("courses");
// Create an empty filter
var filter = new BsonDocument();
// Use the empty filter to get all courses from the database
return await collection.Find(filter).ToListAsync();
}
}
上面的代码从数据库中获取内容,下面的代码 - 在我的中找到Form1.cs
- 将其放入列表框内。
private void FillCourseList() {
Task<List<Course>> courseTask = MongoDBController.GetCourses();
MessageBox.Show("Fetching worked (yay!)");
// get the result
List<Course> result = courseTask.Result;
// Show every course found in the resultset
foreach (Course s in result) {
listBox_overview_vakken.Items.Add(s);
}
}
现在如果我删除获取成功(耶!)弹出我的列表框永远不会被填满。
我究竟做错了什么?
正如亚历克斯善意指出的那样,这个问题的解决方案是使FillCourseList
也是异步的。这允许程序在从数据库获取数据的同时继续运行。我之前遇到的阻塞呼叫显然是问题的原因。这确实增加了需要线程安全调用 https://msdn.microsoft.com/en-us/library/ms171728%28v=vs.80%29.aspx但到 Windows 窗体。
private delegate void SetListCallback(List<Course> result);
private async Task GetCourseList() {
Task<List<Course>> courseTask = MongoDBController.GetCourses();
List<Course> result = await courseTask.ConfigureAwait(false);
// When finished, fill the listbox
FillCourseList(result);
}
private void FillCourseList(List<Course> result) {
// If the calling thread's ID doesn't match the creating thread's ID
// Invoke this method on the correct thread via the delegate
if (this.listBox_overview_vakken.InvokeRequired) {
SetListCallback d = new SetListCallback(FillCourseList);
this.Invoke(d, result);
} else {
foreach (Course s in result) {
listBox_overview_vakken.Items.Add(s);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)